How To Accept a File POST

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

    Toward this same directions, I'm posting a client and server snipets that send Excel Files using WebApi, c# 4:

    public static void SetFile(String serviceUrl, byte[] fileArray, String fileName)
    {
        try
        {
            using (var client = new HttpClient())
            {
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    using (var content = new MultipartFormDataContent())
                    {
                        var fileContent = new ByteArrayContent(fileArray);//(System.IO.File.ReadAllBytes(fileName));
                        fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                        {
                            FileName = fileName
                        };
                        content.Add(fileContent);
                        var result = client.PostAsync(serviceUrl, content).Result;
                    }
            }
        }
        catch (Exception e)
        {
            //Log the exception
        }
    }
    

    And the server webapi controller:

    public Task<IEnumerable<string>> Post()
    {
        if (Request.Content.IsMimeMultipartContent())
        {
            string fullPath = HttpContext.Current.Server.MapPath("~/uploads");
            MyMultipartFormDataStreamProvider streamProvider = new MyMultipartFormDataStreamProvider(fullPath);
            var task = Request.Content.ReadAsMultipartAsync(streamProvider).ContinueWith(t =>
            {
                if (t.IsFaulted || t.IsCanceled)
                        throw new HttpResponseException(HttpStatusCode.InternalServerError);
    
                var fileInfo = streamProvider.FileData.Select(i =>
                {
                    var info = new FileInfo(i.LocalFileName);
                    return "File uploaded as " + info.FullName + " (" + info.Length + ")";
                });
                return fileInfo;
    
            });
            return task;
        }
        else
        {
            throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotAcceptable, "Invalid Request!"));
        }
    }
    

    And the Custom MyMultipartFormDataStreamProvider, needed to customize the Filename:

    PS: I took this code from another post http://www.codeguru.com/csharp/.net/uploading-files-asynchronously-using-asp.net-web-api.htm

    public class MyMultipartFormDataStreamProvider : MultipartFormDataStreamProvider
    {
        public MyMultipartFormDataStreamProvider(string path)
            : base(path)
        {
    
        }
    
        public override string GetLocalFileName(System.Net.Http.Headers.HttpContentHeaders headers)
        {
            string fileName;
            if (!string.IsNullOrWhiteSpace(headers.ContentDisposition.FileName))
            {
                fileName = headers.ContentDisposition.FileName;
            }
            else
            {
                fileName = Guid.NewGuid().ToString() + ".data";
            }
            return fileName.Replace("\"", string.Empty);
        }
    }
    
    0 讨论(0)
  • 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);
    }
    
    0 讨论(0)
  • 2020-11-22 10:19

    Here are two ways to accept a file. One using in memory provider MultipartMemoryStreamProvider and one using MultipartFormDataStreamProvider which saves to a disk. Note, this is only for one file upload at a time. You can certainty extend this to save multiple-files. The second approach can support large files. I've tested files over 200MB and it works fine. Using in memory approach does not require you to save to disk, but will throw out of memory exception if you exceed a certain limit.

    private async Task<Stream> ReadStream()
    {
        Stream stream = null;
        var provider = new MultipartMemoryStreamProvider();
        await Request.Content.ReadAsMultipartAsync(provider);
        foreach (var file in provider.Contents)
        {
            var buffer = await file.ReadAsByteArrayAsync();
            stream = new MemoryStream(buffer);
        }
    
        return stream;
    }
    
    private async Task<Stream> ReadLargeStream()
    {
        Stream stream = null;
        string root = Path.GetTempPath();
        var provider = new MultipartFormDataStreamProvider(root);
        await Request.Content.ReadAsMultipartAsync(provider);
        foreach (var file in provider.FileData)
        {
            var path = file.LocalFileName;
            byte[] content = File.ReadAllBytes(path);
            File.Delete(path);
            stream = new MemoryStream(content);
        }
    
        return stream;
    }
    
    0 讨论(0)
  • 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<IHttpActionResult> 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();
    }
    
    0 讨论(0)
  • 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:

    <form>
        <input type="file" id="myfile"/>  
        <input type="button" onclick="uploadFile();" value="Upload" />
    </form>
    <script type="text/javascript">
        function uploadFile() {        
            var xhr = new XMLHttpRequest();                 
            var file = document.getElementById('myfile').files[0];
            xhr.open("POST", "api/myfileupload");
            xhr.setRequestHeader("filename", file.name);
            xhr.send(file);
        }
    </script>
    
    0 讨论(0)
  • 2020-11-22 10:23

    I had a similar problem for the preview Web API. Did not port that part to the new MVC 4 Web API yet, but maybe this helps:

    REST file upload with HttpRequestMessage or Stream?

    Please let me know, can sit down tomorrow and try to implement it again.

    0 讨论(0)
提交回复
热议问题