How To Accept a File POST

前端 未结 13 1619
深忆病人
深忆病人 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 09:58

    see http://www.asp.net/web-api/overview/formats-and-model-binding/html-forms-and-multipart-mime#multipartmime, although I think the article makes it seem a bit more complicated than it really is.

    Basically,

    public Task 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(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; 
    } 
    

提交回复
热议问题