我使用了@scott对这个问题的回答中的以下代码。我如何将图像上传到ServiceStack服务?
[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" }});
}
我在我的DTO和Android应用程序中使用了这个,但当我尝试发送它时,它总是失败,并出现以下服务器错误:
{"ResponseStatus": {"ErrorCode":"UnauthorizedAccessException","Message":"'C:\Windows\SysWOW64\inetsrv\a.png' path denied.", 'C:WindowsSysWOW64inetsrva.png' path denied.
有人能分享Mondroid ServiceStack图片上传示例吗?
谢谢。
示例代码没有任何问题,您从我在这里给出的答案中得到的,您在Monodroid客户端中使用了它。它使用ServiceStack PCL库在Mondroid上工作,无需修改。
Monodroid:
无需修改。
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" }});
}
服务器文件权限错误:
上载到ServiceStack服务时收到的错误消息显示,您的服务器进程无权将文件写入此目录C:WindowsSysWOW64inetsrv
。
{
"ResponseStatus":
{
"ErrorCode":"UnauthorizedAccessException",
"Message":"'C:WindowsSysWOW64inetsrva.png' path denied."
}
}
您需要更新服务器端服务,以便将文件写入服务有权限访问的路径。
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");
// Replace with a path you have permission to write to
var path = @"c:tempimage.png";
// Save the file
Request.Files[0].SaveTo(path);
// Maybe store the tags (or any other data in the request)
// request.Tags
return true;
}
}
如果你修复了权限错误,你会发现它是有效的。