将文件从MVC发布到WEB API

将文件从MVC发布到WEB API

问题描述:

我有一个瘦的ASP.NET MVC客户端和一个WEB API后端.我需要在MVC端接收excel文件,然后将其发送到WEB API控制器,而无需进行任何更改.如何以最简单的方式实现它?

I have a thin ASP.NET MVC client and a WEB API back end. I need to receive excel file on MVC side and the send it to WEB API controller without any changes. How can I achieve it in most simple way?

[HttpPost]
public ActionResult UploadExcelFile(HttpPostedFileBase file)
{
   //call web api here 
} 

现在我正在考虑创建一个看起来像这样的UploadFileRequest:

Right now I'm thinking of creating an UploadFileRequest that will look like this:

public class UploadFileRequest 
{
    public byte[] byteData { get; set; }
}

并将文件作为字节数组传递,但是效率极低.

and pass file as byte array, however this looks extremely inefficient.

我创建了一个示例,用于将文件从MVC控制器上传到Web Api控制器,并且运行良好

I have created a sample for uploading files from MVC controller to Web Api controller, and it's working perfectly

MVC控制器:

    [ActionName("FileUpload")]
    [HttpPost]
    public ActionResult FileUpload_Post()
    {
        if (Request.Files.Count > 0)
        {
            var file = Request.Files[0];

            using (HttpClient client = new HttpClient())
            {
                using (var content = new MultipartFormDataContent())
                {
                    byte[] fileBytes = new byte[file.InputStream.Length + 1];                         
                    file.InputStream.Read(fileBytes, 0, fileBytes.Length);
                    var fileContent = new ByteArrayContent(fileBytes);
                    fileContent.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment") { FileName = file.FileName };
                    content.Add(fileContent);
                    var result = client.PostAsync(requestUri, content).Result;
                    if (result.StatusCode == System.Net.HttpStatusCode.Created)
                    {
                        ViewBag.Message= "Created";
                    }
                    else
                    {
                        ViewBag.Message= "Failed";
                    }
                }
            }
        }
        return View();
    }

Web Api控制器:

Web Api controller :

    [HttpPost]
    public HttpResponseMessage Upload()
    {
        if(!Request.Content.IsMimeMultipartContent())
        {
            throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
        }
        if (System.Web.HttpContext.Current.Request.Files.Count > 0)
        {
            var file = System.Web.HttpContext.Current.Request.Files[0];
            ....
            // save the file
            ....
            return new HttpResponseMessage(HttpStatusCode.Created);
        }
        else
        {
            return new HttpResponseMessage(HttpStatusCode.BadRequest);
        }
    }

有关在Web Api中保存文件的更多信息,请参考

For more information on saving file in Web Api, refer Web API: File Upload

希望对某人有帮助!