ServiceStack客户端添加附件

时间:2011-11-28 13:57:59

标签: c# soap servicestack

我正在使用ServiceStack.ServiceClient.Web.XmlServiceClient连接到Web服务。有没有办法在请求中添加附件?

更多信息:

我想要做的是避免使用Microsoft.Web.Services2,因为我使用的是Mono。我正在尝试上传XML数据文件以及XML请求。就像这个问题一样: Upload report unit via webservice in C# .net to jasperserver

1 个答案:

答案 0 :(得分:14)

要上传文件,最好(也是最快)的方法是将其编码为普通请求变量,只需将其作为普通HTTP上传到Content Services multipart / form-data ,即HTML表单当前如何将文件发送到网址。

ServiceStack内置支持以这种方式处理上传文件,其中包含如何在ServiceStack's RestFiles example project中执行此操作的完整示例。

要使用ServiceClient上传文件,您可以使用 .PostFile< T>()方法seen in this example

var fileToUpload = new FileInfo(FilesRootDir + "TESTUPLOAD.txt");

var response = restClient.PostFile<FilesResponse>(WebServiceHostUrl + "files/README.txt",
    fileToUpload, MimeTypes.GetMimeType(fileToUpload.Name));

所有上传的文件均可通过base.RequestContext.Files集合提供,您可以easily process with the SaveTo() method(作为流或文件)。

foreach (var uploadedFile in base.RequestContext.Files)
{
    var newFilePath = Path.Combine(targetDir.FullName, uploadedFile.FileName);
    uploadedFile.SaveTo(newFilePath);
}

同样与返回文件响应(作为附件或直接)相关,您只需要return the FileInfo in a HttpResult like

return new HttpResult(FileInfo, asAttachment:true);

多个文件上传

您还可以使用所有.NET服务客户端中提供的PostFilesWithRequest API在单个HTTP请求中上载多个流。它支持使用 QueryString 的任意组合填充Request DTO 除了多个文件上传数据流之外,还有POST FormData ,例如:

using (var stream1 = uploadFile1.OpenRead())
using (var stream2 = uploadFile2.OpenRead())
{
    var client = new JsonServiceClient(baseUrl);
    var response = client.PostFilesWithRequest<MultipleFileUploadResponse>(
        "/multi-fileuploads?CustomerId=123",
        new MultipleFileUpload { CustomerName = "Foo,Bar" },
        new[] {
            new UploadFile("upload1.png", stream1),
            new UploadFile("upload2.png", stream2),
        });
}

仅使用类型化请求DTO的示例。 JsonHttpClient还包括每个PostFilesWithRequest API的异步等效项:

using (var stream1 = uploadFile1.OpenRead())
using (var stream2 = uploadFile2.OpenRead())
{
    var client = new JsonHttpClient(baseUrl);
    var response = await client.PostFilesWithRequestAsync<MultipleFileUploadResponse>(
        new MultipleFileUpload { CustomerId = 123, CustomerName = "Foo,Bar" },
        new[] {
            new UploadFile("upload1.png", stream1),
            new UploadFile("upload2.png", stream2),
        });
}