HttpRequest.Files is empty when posting file through HttpClient

前端 未结 4 2044
無奈伤痛
無奈伤痛 2020-12-06 02:29

Server-side:

    public HttpResponseMessage Post([FromUri]string machineName)
    {
        HttpResponseMessage result = null;
        var httpRequest = Http         


        
4条回答
  •  眼角桃花
    2020-12-06 02:39

    You shouldn't use HttpContext for getting the files in ASP.NET Web API. Take a look at this example written by Microsoft (http://code.msdn.microsoft.com/ASPNET-Web-API-File-Upload-a8c0fb0d/sourcecode?fileId=67087&pathId=565875642).

    public class UploadController : ApiController 
    { 
        public async Task PostFile() 
        { 
            // Check if the request contains multipart/form-data. 
            if (!Request.Content.IsMimeMultipartContent()) 
            { 
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); 
            } 
    
            string root = HttpContext.Current.Server.MapPath("~/App_Data"); 
            var provider = new MultipartFormDataStreamProvider(root); 
    
            try 
            { 
                StringBuilder sb = new StringBuilder(); // Holds the response body 
    
                // Read the form data and return an async task. 
                await Request.Content.ReadAsMultipartAsync(provider); 
    
                // This illustrates how to get the form data. 
                foreach (var key in provider.FormData.AllKeys) 
                { 
                    foreach (var val in provider.FormData.GetValues(key)) 
                    { 
                        sb.Append(string.Format("{0}: {1}\n", key, val)); 
                    } 
                } 
    
                // This illustrates how to get the file names for uploaded files. 
                foreach (var file in provider.FileData) 
                { 
                    FileInfo fileInfo = new FileInfo(file.LocalFileName); 
                    sb.Append(string.Format("Uploaded file: {0} ({1} bytes)\n", fileInfo.Name, fileInfo.Length)); 
                } 
                return new HttpResponseMessage() 
                { 
                    Content = new StringContent(sb.ToString()) 
                }; 
            } 
            catch (System.Exception e) 
            { 
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e); 
            } 
        } 
    
    }
    

提交回复
热议问题