How do I get Multiple raw Http Request Input Strea

2019-06-03 00:56发布

问题:

I am trying upload multiple file using service stack. Below code is working fine for one file upload. I want to upload multiple file. Please let me know what change should be required so that below codes work for multiple files upload also.

 public class Hello : IRequiresRequestStream
    {
        Stream RequestStream { get; set; }
    }

At client side I am using 'multipart/form-data' for file upload.

回答1:

See the documentation on Uploading Files, IRequiresRequestStream is only for accessing the Request Body as a Stream of Bytes, to process multiple files uploaded with multipart/form-data use the base.Request.Files property instead, e.g:

Uploading Files

You can access uploaded files independently of the Request DTO using Request.Files. e.g:

public object Post(MyFileUpload request)
{
    if (this.Request.Files.Length > 0)
    {
        var uploadedFile = base.Request.Files[0];
        uploadedFile.SaveTo(MyUploadsDirPath.CombineWith(file.FileName));
    }
    return HttpResult.Redirect("/");
}

ServiceStack's imgur.servicestack.net example shows how to access the byte stream of multiple uploaded files, e.g:

public object Post(Upload request)
{
    foreach (var uploadedFile in base.Request.Files
       .Where(uploadedFile => uploadedFile.ContentLength > 0))
    {
        using (var ms = new MemoryStream())
        {
            uploadedFile.WriteTo(ms);
            WriteImage(ms);
        }
    }
    return HttpResult.Redirect("/");
}