How To Accept a File POST

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

    I'm surprised that a lot of you seem to want to save files on the server. Solution to keep everything in memory is as follows:

    [HttpPost("api/upload")]
    public async Task Upload()
    {
        if (!Request.Content.IsMimeMultipartContent())
            throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); 
    
        var provider = new MultipartMemoryStreamProvider();
        await Request.Content.ReadAsMultipartAsync(provider);
        foreach (var file in provider.Contents)
        {
            var filename = file.Headers.ContentDisposition.FileName.Trim('\"');
            var buffer = await file.ReadAsByteArrayAsync();
            //Do whatever you want with filename and its binary data.
        }
    
        return Ok();
    }
    

提交回复
热议问题