我有图像的路径,并使用以下代码将其发送到我的服务器;
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 ();
但是代码不起作用,图像没有附加。我在这里做错了什么?
答案 0 :(得分:3)
multipart/form-data
需要边界:将HttpWebRequest
与multipart/form-data
一起使用时,您需要指定内容的边界。这是相当多的工作,如果您不理解它,很容易导致损坏的上传。但是this question here涵盖了如何执行此操作。
但是当您使用ServiceStack后端时,最好的方法是在Android应用程序中使用ServiceStack.Client PCL library,这提供了易于使用的JsonServiceClient
。 See this example表示使用ServiceStack演示的完整Android版。
所以给出一个简单的上传服务(在服务器端):
[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;
}
}
然后在Android应用中使用JsonServiceClient
,那么您只需要这样做:
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" }});
}
我希望这会有所帮助。