mvc调用webapi上传图片或文件

<后台>webapi

public void UploadFile()
{
if (HttpContext.Current.Request.Files.AllKeys.Any())
{
// Get the uploaded image from the Files collectionvar
var httpPostedFile = HttpContext.Current.Request.Files["UploadedImage"];
if (httpPostedFile != null)
{
// Validate the uploaded image(optional)// Get the complete file path
var fileSavePath = Path.Combine(HttpContext.Current.Server.MapPath("~/UploadedFiles"),httpPostedFile.FileName );
// Save the uploaded file to"UploadedFiles" folder
httpPostedFile.SaveAs(fileSavePath);
filepath = Path.Combine("~/UploadedFiles", httpPostedFile.FileName);
}
}
}

//添加
[HttpPost]
public int Gadd(GoodsModel model)
{
model.GImg = filepath?.Replace("~", "").Replace("\", "/");
return bll.Gadd(model);
}

//把图片保存到webapi的UploadedFiles文件夹中,然后mvc调用这个文件路径

<前台> MVC

function Uploag() {
//上传文件
var fdate = new FormData();
var file = $("#fileUpload").get(0).files;
//如果文件存在
if (file != null) {
//自定义一个文件名称并添加到尾部
fdate.append("UploadedImage", file[0]);

}
var ajaxRequest = $.ajax({
url: "http://localhost:54489/api/Goods/UploadFile",
type: "post",
processData: false,
contentType: false,
data: fdate
});
}

原文地址:https://www.cnblogs.com/lishiyiya/p/13581559.html