简体   繁体   English

使用RestSharp将文件从MVC控制器上载到Web API

[英]File upload from MVC controller to Web API using RestSharp

One of the features of my web application is the ability of the users to upload markdown files. 我的Web应用程序的一个功能是用户上传markdown文件的能力。 I'd like to pass the file from a MVC controller to a Web API controller, afterwards the Web API will save the markdown file on a specific project folder. 我想将文件从MVC控制器传递到Web API控制器,之后Web API会将markdown文件保存在特定的项目文件夹中。 I'd like to know if it's possible. 我想知道是否有可能。 If yes, how to do it. 如果是的话,怎么做。

So for what I had in mind is having the MVC controller take a HttpPostedFileBase parameter and afterwards use RestSharp's request.AddFile() to send the file to the Web API controller. 因此,我想到的是让MVC控制器获取HttpPostedFileBase参数,然后使用RestSharp的request.AddFile()将文件发送到Web API控制器。

MVC Controller MVC控制器

[HttpPost]
public ActionResult Upload(HttpPostedFileBase upload)
{
    var client = new RestClient("http://localhost:4000/api/beneficiaries");
    var request = new RestRequest(Method.POST);
    //todo send file to web API
    var response = client.Execute(request);
    return View();
}

This should work, even if I haven't tested it: 这应该有效,即使我没有测试过:

request.AddFile(upload.FileName, upload.InputStream.CopyTo, upload.ContentType);

Depending of the api target method, and if you need some parameters sent with it, you might need: 根据api目标方法,如果您需要使用它发送一些参数,您可能需要:

request.AddFile(upload.FileName, upload.InputStream.CopyTo);
request.AddHeader("Content-Type", "multipart/form-data");

request.AddParameter("filename", upload.FileName, ParameterType.RequestBody);
request.AddParameter("otherParameter", "Something here...", ParameterType.RequestBody);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM