How To Accept a File POST

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

    See the code below, adapted from this article, which demonstrates the simplest example code I could find. It includes both file and memory (faster) uploads.

    public HttpResponseMessage Post()
    {
        var httpRequest = HttpContext.Current.Request;
        if (httpRequest.Files.Count < 1)
        {
            return Request.CreateResponse(HttpStatusCode.BadRequest);
        }
    
        foreach(string file in httpRequest.Files)
        {
            var postedFile = httpRequest.Files[file];
            var filePath = HttpContext.Current.Server.MapPath("~/" + postedFile.FileName);
            postedFile.SaveAs(filePath);
            // NOTE: To store in memory use postedFile.InputStream
        }
    
        return Request.CreateResponse(HttpStatusCode.Created);
    }
    

提交回复
热议问题