如何接受一个文件POST - ASP.Net MVC 4的WebAPI [英] How To Accept a File POST - ASP.Net MVC 4 WebAPI
问题描述
我使用asp.net的MVC 4的WebAPI测试建立一个休息服务。我需要能够接受张贴的图片/文件从客户端应用程序。这是可能使用的WebAPI?下面是我如何行动目前正在使用。有谁知道一个例子这应该是如何工作的?
[HttpPost]
公共字符串ProfileImagePost(HttpPostedFile profileImage)
{
字符串[] =扩展{.JPG,.JPEG,名为.gif,.BMP,png格式};
如果(extensions.Any(X =>!x.Equals(Path.GetExtension(profileImage.FileName.ToLower()),StringComparison.OrdinalIgnoreCase)))
{
抛出新的Htt presponseException(无效的文件类型,则httpStatus code.BadRequest);
} //其他code到这里 返回/path/to/image.png
}
看<一个href=\"http://www.asp.net/web-api/overview/working-with-http/sending-html-form-data,-part-2\">http://www.asp.net/web-api/overview/working-with-http/sending-html-form-data,-part-2,虽然我觉得文章使它看起来有点复杂得多,它确实是。
基本上,
公共任务&LT; Htt的presponseMessage&GT; PostFile()
{
HTT prequestMessage请求= this.Request;
如果(!request.Content.IsMimeMultipartContent())
{
抛出新的Htt presponseException(的HTTPStatus code.UnsupportedMediaType);
} 串根= System.Web.HttpContext.Current.Server.MapPath(〜/ App_Data文件/上传);
VAR提供商=新MultipartFormDataStreamProvider(根); VAR任务= request.Content.ReadAsMultipartAsync(供应商)。
ContinueWith&LT; Htt的presponseMessage&GT;(O = GT;
{ 字符串文件1 = provider.BodyPartFileNames.First()值。
//这是该文件被保存在服务器上的文件名 返回新的Htt presponseMessage()
{
内容=新的StringContent(文件上传。)
};
}
);
返回任务;
}
I'm using asp.net mvc 4 webapi beta to build a rest service. I need to be able to accept POSTed images/files from client applications. Is this possible using the webapi? Below is how action I am currently using. Does anyone know of an example how this should work?
[HttpPost]
public string ProfileImagePost(HttpPostedFile profileImage)
{
string[] extensions = { ".jpg", ".jpeg", ".gif", ".bmp", ".png" };
if (!extensions.Any(x => x.Equals(Path.GetExtension(profileImage.FileName.ToLower()), StringComparison.OrdinalIgnoreCase)))
{
throw new HttpResponseException("Invalid file type.", HttpStatusCode.BadRequest);
}
// Other code goes here
return "/path/to/image.png";
}
see http://www.asp.net/web-api/overview/working-with-http/sending-html-form-data,-part-2, although I think the article makes it seem a bit more complicated than it really is.
Basically,
public Task<HttpResponseMessage> PostFile()
{
HttpRequestMessage request = this.Request;
if (!request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
string root = System.Web.HttpContext.Current.Server.MapPath("~/App_Data/uploads");
var provider = new MultipartFormDataStreamProvider(root);
var task = request.Content.ReadAsMultipartAsync(provider).
ContinueWith<HttpResponseMessage>(o =>
{
string file1 = provider.BodyPartFileNames.First().Value;
// this is the file name on the server where the file was saved
return new HttpResponseMessage()
{
Content = new StringContent("File uploaded.")
};
}
);
return task;
}
这篇关于如何接受一个文件POST - ASP.Net MVC 4的WebAPI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!