小编典典

如何接受文件POST

c#

我正在使用asp.net mvc 4 webapi
beta来构建REST服务。我需要能够接受来自客户端应用程序的POST图像/文件。使用webapi是否可以?以下是我当前正在使用的操作。有谁知道一个例子,这应该如何工作?

[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";
}

阅读 344

收藏
2020-05-19

共1个答案

小编典典

看到http://www.asp.net/web-api/overview/formats-and-model-binding/html-forms-
and-multipart-
mime#multipartmime,尽管我认为这篇文章使它看起来比确实是。

基本上,

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; 
}
2020-05-19