java - 如何编写用于文件上传的 MVC Web Api Post 方法

标签 java android asp.net-mvc http-post httprequest

我正在关注 this 关于从 android 将文件上传到服务器的教程,但我似乎无法在服务器端获取正确的代码。有人可以帮我编写可与 android java uploader 一起使用的 Web Api post 方法吗?我当前的 Web api Controller 类如下所示:

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)
        {
        }
    }
}

由于截止日期是星期二,我非常渴望让这项工作顺利进行。如果有人可以提供帮助,我们将不胜感激。

最佳答案

您可以将文件发布为 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);
        }
    }

关于java - 如何编写用于文件上传的 MVC Web Api Post 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19212419/

相关文章:

java - 如果传感器更新(太)慢,服务就会被终止

具有多种实现的 Java 通用接口(interface)

android - 使用 Android 23+ 确定 list 中是否存在权限

java - 不让 AdMob 广告请求焦点?

c# - Func<T> Inkover 错误无法从用法中推断出来。尝试明确指定类型参数

java - 如何使用 Apache OpenNLP 分析 Java Web 应用程序中的文本?

java - 为什么要使用JSTL?当我们在JSP文件中使用带有连接字符串的数据库连接来获取servlet发送的数据时会有什么危害

java - android.content.res.Resources$NotFoundException : Resource ID #0x0 java exception

c# - 如何使用 Entity Framework 使用外键保存新记录?

asp.net-mvc - ASP.NET MVC 中的静态文件路由