gpt4 book ai didi

c# - 在 web Api 和 angularJS 中上传文件和表单数据

转载 作者:太空狗 更新时间:2023-10-29 18:24:32 25 4
gpt4 key购买 nike

我正在遵循此 blog 中的指南关于如何发布表单数据和一份文件。我正在尝试将文件上传到服务器上的目录中已完成以下操作,但无法正常工作。

这是发布功能

[HttpPost]
public async Task<HttpResponseMessage> UploadFile(HttpRequestMessage request)
{
String root = HttpContext.Current.Server.MapPath("~/Logo/");

if (!request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}

var data = await Request.Content.ParseMultipartAsync();
var httpRequest = HttpContext.Current.Request;

if (data.Files.ContainsKey("file"))
{

var file = data.Files["file"].File; // this is getting the file
var fileName = data.Files["file"].Filename; // this is getting the fileName
// System.Web.HttpPostedFile filePost = data.Files["file"];
String a = root + "" + Path.GetFileName(fileName);
string b = a;
var postedFile = fileName; // this is not working
var filePath = HttpContext.Current.Server.MapPath("~/Logo/" + fileName); // can someone help please
postedFile.SaveAs(filePath); // I

}

if (data.Fields.ContainsKey("description"))
{
var description = data.Fields["description"].Value;
}

return new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent("Thank you for uploading the file...")
};
}

如何将文件保存到服务器上的目录中?

最佳答案

目前我正在使用以下代码上传图像文件,但它也适用于任何类型的文件:

public string UploadImage()
{
HttpRequestMessage request = this.Request;
if (!request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(new HttpResponseMessage((HttpStatusCode.UnsupportedMediaType)));
}
var context = HttpContext.Current.Request;
if (context.Files.Count > 0)
{
var resourcePhoto = new PhotoHelper(HttpContext.Current.Server.MapPath("~"));
var file = context.Files.AllKeys.FirstOrDefault();
var result = resourcePhoto.SaveResourceImage(context.Files[file], User.Identity.Name);
return result;
}
else
{
return null;
}
}

SaveResourceImage 中,我执行以下操作:

 postedFile.SaveAs(resultPath);

就是这样。

关于c# - 在 web Api 和 angularJS 中上传文件和表单数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37414415/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com