How do I upload an image to a ServiceStack service?

為{幸葍}努か 提交于 2019-12-10 11:48:00

问题


I have the path of an image, and use the following code to send it to my server;

HttpWebRequest client = (HttpWebRequest)WebRequest.Create("http://212.175.132.168/service/api/upload/cab.jpg");
client.Method = WebRequestMethods.Http.Post; 

// the following 4 rows enable streaming 
client.AllowWriteStreamBuffering = false;
client.SendChunked = true;
client.ContentType = "multipart/form-data;";
client.Timeout = int.MaxValue;

using (FileStream fileStream = System.IO.File.OpenRead (filePath)) {
    fileStream.Copy (client.GetRequestStream ());
}

var response = new StreamReader (client.GetResponse ().GetResponseStream ()).ReadToEnd ();

But the code doesn't work, image isn't attached. What I am I doing wrong here?


回答1:


HttpWebRequest + multipart/form-data needs boundaries:

By using HttpWebRequest with multipart/form-data requires that you specify the boundaries of your content. Which is rather a lot of work and can easily cause corrupt uploads if you don't understand it. However this question here covers how to do it.

Use the PCL ServiceStack.Client:

But as you are using a ServiceStack backend, then the best approach is to use the ServiceStack.Client PCL library in your Android application, which provides the easy to use JsonServiceClient. See this example for a full Android with ServiceStack demonstration.

So given a simple Upload Service (on your server side):

[Route("/upload","POST")]
public class UploadFileRequest
{
    // Example of other properties you can send with the request
    public string[] Tags { get; set; }
}

class MyFileService : Service
{
    public bool Post(UploadFileRequest request)
    {
        // Check a file has been attached
        if(Request.Files == null || Request.Files.Length == 0)
            throw new HttpError(400, "Bad Request", "No file has been uploaded");

        // Save the file
        Request.Files[0].SaveTo(Request.Files[0].FileName);

        // Maybe store the tags (or any other data in the request)
        // request.Tags

        return true;
    }
}

Then with the JsonServiceClient in your Android app, then your simply need to do this:

var filename = "cab.jpg"; // The path of the file to upload
var client = new JsonServiceClient("http://212.175.132.168/service/api/");
using(var fileStream = File.OpenRead(filename))
{
    client.PostFileWithRequest<bool>(fileStream, "cab.jpg", new UploadFileRequest { Tags = new[] { "Cab", "Taxis", "NewYork", "Yellow" }});
}

I hope this helps.



来源:https://stackoverflow.com/questions/25886245/how-do-i-upload-an-image-to-a-servicestack-service

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