如何将参数和上传图像同时传递到一个网页 api
本文关键字:api 网页 一个 参数 图像 | 更新日期: 2023-09-27 18:34:13
我使用此控制器:
public class uploadphotosController : ApiController
{
public Task<HttpResponseMessage> Post( )
{
// Check if the request contains multipart/form-data.
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
string root =HostingEnvironment.MapPath("~/photos");//Burdaki app data klasoru degisecek
var provider = new MultipartFormDataStreamProvider(root);
// Read the form data and return an async task.
var task = Request.Content.ReadAsMultipartAsync(provider).
ContinueWith<HttpResponseMessage>(t =>
{
if (t.IsFaulted || t.IsCanceled)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, t.Exception);
}
// This illustrates how to get the file names.
foreach (MultipartFileData file in provider.FileData)
{
string fileName = file.LocalFileName;
string originalName = file.Headers.ContentDisposition.FileName;
FileInfo file2 = new FileInfo(fileName);
file2.CopyTo(Path.Combine(root, originalName.TrimStart('"').TrimEnd('"')), true);
file2.Delete();
//Trace.WriteLine(file.Headers.ContentDisposition.FileName);
// Trace.WriteLine("Server file path: " + file.LocalFileName);
}
return Request.CreateResponse(HttpStatusCode.OK);
});
return task;
}
}
我在WebApiConfig中使用它.cs
config.Routes.MapHttpRoute(
name: "DefaultApi_uploadphotos",
routeTemplate: "api/{ext}/uploadphotos/",
defaults: new
{
controller = "uploadphotos"
});
它工作正常,但我需要同时上传带有发送电子邮件和密码的图像。因为如果用户存在,我想上传图像。以我的方式,每个人都以用户身份上传照片。我想将图像和一些参数(如电子邮件和密码)发送到同一个 Web API。
我该怎么做?
提前致谢
什么对我有用:
public async Task<HttpResponseMessage> PostFile(string a, string b)
{
var requestStream = await Request.Content.ReadAsStreamAsync();
...
}
路由:
config.Routes.MapHttpRoute(
name: "ControllerApi",
routeTemplate: "/{controller}/{a}/{b}"
);
发送文件:
var request = (HttpWebRequest) HttpWebRequest.Create("http://host/controller/hello/world");
request.Method = "POST";
var stream = request.GetRequestStream();
var docFile = File.OpenRead(sourceFile);
docFile.CopyTo(stream);
docFile.Close();
stream.Close();
var response = request.GetResponse();