后端webapi:
[HttpPost]
[Route("api/lili/imgupload")]
public string Imgupload()
{
//文件保存目录路径
string SaveTempPath = "/upload/head/";
String dirTempPath = HttpContext.Current.Server.MapPath(SaveTempPath);
if (!Directory.Exists(dirTempPath))
{
Directory.CreateDirectory(dirTempPath);
}
HttpRequest request = System.Web.HttpContext.Current.Request;
HttpFileCollection FileCollect = request.Files;
HttpPostedFile FileSave = FileCollect[0]; //因为只有图片 使用是0 如果是多个文件 可以使用foreach循环 前端是否from表单上传
string imgName = DateTime.Now.ToString("yyyyMMddhhmmss");
string imgPath = SaveTempPath + imgName + FileSave.FileName; //通过此对象获取文件名
string AbsolutePath = System.Web.HttpContext.Current.Server.MapPath(imgPath);
FileSave.SaveAs(AbsolutePath); //将上传的东西保存
return "";
}
前端html:
<div>
<input type="file" name="uploadImage" id="uploadImage">
<input type="button" id="btn" value="上传" />
</div>
前端jq:
$("#btn").click(function () {
var formData = new FormData();
formData.append("FileUpload1", document.getElementById('uploadImage').files[0]);
$.ajax({
url: 'https://localhost:44349/api/lili/imgupload',
type: "POST",
data: formData,
contentType: false,
processData: false,
success: function (data) {
alert(JSON.stringify(data));
}
});
})