How To Accept a File POST

前端 未结 13 1422
深忆病人
深忆病人 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:21

    Here is a quick and dirty solution which takes uploaded file contents from the HTTP body and writes it to a file. I included a "bare bones" HTML/JS snippet for the file upload.

    Web API Method:

    [Route("api/myfileupload")]        
    [HttpPost]
    public string MyFileUpload()
    {
        var request = HttpContext.Current.Request;
        var filePath = "C:\\temp\\" + request.Headers["filename"];
        using (var fs = new System.IO.FileStream(filePath, System.IO.FileMode.Create))
        {
            request.InputStream.CopyTo(fs);
        }
        return "uploaded";
    }
    

    HTML File Upload:

提交回复
热议问题