ServiceStack - Upload files with stream and with U

2019-07-23 10:18发布

问题:

I have got the following DTOs:

[Route("/images/{imageId}/upload", "PUT")]
public class GetImageWithStream : IRequiresRequestStream
{
    public Stream RequestStream { get; set; }
    public string imageId { get; set; }
}

///images/{imageId}/upload?url={imageUrl}
[Route("/images/{imageId}/upload", "PUT")]
public class GetImageWithUri 
{
    public string imageId { get; set; }
    public string url { get; set; }
}

/images/1/upload -> this should routed to the first DTO

/images/1/upload?url=something.jpg -> this should routed to the second DTO

Now both of them routed to the first DTO and in case of the second path the stream is a NullStream of course. With the first path the stream is good but the imageId is null.

Or I can imagine something like this:

[Route("/images/{imageId}/upload", "PUT")]
public class GetImageWithStream : IRequiresRequestStream
{
    public Stream RequestStream { get; set; }
    public string imageId { get; set; }
    public string url { get; set; }
}

Is it possible to handle the same PATH with different ways in ServiceStack?

回答1:

Using a IRequiresRequestStream tells ServiceStack to skip the Request Binding and to let your Service read from the un-buffered request stream.

But if you just want to handle file uploads you can access uploaded files independently of the Request DTO using RequestContext.Files. e.g:

public object Post(MyFileUpload request)
{
    if (this.Request.Files.Length > 0)
    {
        var uploadedFile = this.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 Request.Files
       .Where(uploadedFile => uploadedFile.ContentLength > 0))
    {
        using (var ms = new MemoryStream())
        {
            uploadedFile.WriteTo(ms);
            WriteImage(ms);
        }
    }
    return HttpResult.Redirect("/");
}