ServiceStack - Upload files with stream and with Uri

我们两清 提交于 2019-12-24 00:39:13

问题


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("/");
}


来源:https://stackoverflow.com/questions/19311733/servicestack-upload-files-with-stream-and-with-uri

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!