如何编写MVC Web Api Post方法进行文件上传 [英] How to code MVC Web Api Post method for file upload

查看:180
本文介绍了如何编写MVC Web Api Post方法进行文件上传的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在关注 这个 有关从android上传文件到服务器的教程,但我似乎无法在服务器端获得正确的代码。有人可以帮我编写可以使用android java上传器的Web Api post方法吗?我当前的web api控制器类看起来像这样:

I am following this tutorial on uploading files to a server from android, but I cannot seem to get the code right on the server side. Can somebody please help me code the Web Api post method that would work with that android java uploader? My current web api controller class looks like this:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;

namespace WSISWebService.Controllers
{
    public class FilesController : ApiController
    {
        // GET api/files
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET api/files/5
        public string Get(int id)
        {
            return "value";
        }

        // POST api/files
        public string Post([FromBody]string value)
        {
            var task = this.Request.Content.ReadAsStreamAsync();
            task.Wait();
            Stream requestStream = task.Result;

            try
            {
                Stream fileStream = File.Create(HttpContext.Current.Server.MapPath("~/" + value));
                requestStream.CopyTo(fileStream);
                fileStream.Close();
                requestStream.Close();
            }
            catch (IOException)
            {
                //  throw new HttpResponseException("A generic error occured. Please try again later.", HttpStatusCode.InternalServerError);
            }

            HttpResponseMessage response = new HttpResponseMessage();
            response.StatusCode = HttpStatusCode.Created;
            return response.ToString();
        }          

        // PUT api/files/5
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE api/files/5
        public void Delete(int id)
        {
        }
    }
}

我非常渴望让这个工作,因为截止日期是星期二。如果有人可以提供帮助,那将非常感激。

I am pretty desperate to get this working as the deadline is tuesday. If anybody could help that would be much appreciated.

推荐答案

你可以将文件发布为multipart / form-data

you can post a files as multipart/form-data

    // POST api/files
    public async Task<HttpResponseMessage> Post()
    {
        // Check if the request contains multipart/form-data.
        if (!Request.Content.IsMimeMultipartContent())
        {
            throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
        }

        string root = HttpContext.Current.Server.MapPath("~/App_Data");
        var provider = new MultipartFormDataStreamProvider(root);

        string value;

        try
        {
            // Read the form data and return an async data.
            var result = await Request.Content.ReadAsMultipartAsync(provider);

            // This illustrates how to get the form data.
            foreach (var key in provider.FormData.AllKeys)
            {
                foreach (var val in provider.FormData.GetValues(key))
                {
                    // return multiple value from FormData
                    if (key == "value")
                        value = val;
                }
            }                       

            if (result.FileData.Any())
            {                    
                // This illustrates how to get the file names for uploaded files.
                foreach (var file in result.FileData)
                {
                    FileInfo fileInfo = new FileInfo(file.LocalFileName);
                    if (fileInfo.Exists)
                    {
                       //do somthing with file
                    }
                }
            }


            HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, value);
            response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = files.Id }));
            return response;
        }
        catch (System.Exception e)
        {
            return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
        }
    }

这篇关于如何编写MVC Web Api Post方法进行文件上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆