How To Accept a File POST

前端 未结 13 1704
深忆病人
深忆病人 2020-11-22 09:48

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?

13条回答
  •  感动是毒
    2020-11-22 10:05

    I used Mike Wasson's answer before I updated all the NuGets in my webapi mvc4 project. Once I did, I had to re-write the file upload action:

        public Task Upload(int id)
        {
            HttpRequestMessage request = this.Request;
            if (!request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(new HttpResponseMessage(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(o =>
                {
                    FileInfo finfo = new FileInfo(provider.FileData.First().LocalFileName);
    
                    string guid = Guid.NewGuid().ToString();
    
                    File.Move(finfo.FullName, Path.Combine(root, guid + "_" + provider.FileData.First().Headers.ContentDisposition.FileName.Replace("\"", "")));
    
                    return new HttpResponseMessage()
                    {
                        Content = new StringContent("File uploaded.")
                    };
                }
            );
            return task;
        }
    

    Apparently BodyPartFileNames is no longer available within the MultipartFormDataStreamProvider.

提交回复
热议问题