HTML5 中已经可以用 Ajax 上传文件了,而且代码非常简单,借助 FormData
类即可发送文件数据。
前端代码:
<p><input type="file" id="upfile"></p>
<p><input type="button" id="upJS" value="用原生JS上传"></p>
<p><input type="button" id="upJQuery" value="用jQuery上传"></p>
<script> // 原生JS版 document.getElementById("upJS").onclick = function () { /* FormData 是表单数据类 */ var fd = new FormData(); var ajax = new XMLHttpRequest(); fd.append("upload", 1); /* 把文件添加到表单里 */ fd.append("upfile", document.getElementById("upfile").files[0]); ajax.open("post", "/api/Upload", true); ajax.onload = function () { console.log(ajax.responseText); }; ajax.send(fd); } // jQuery版 $('#upJQuery').on('click', function () { var fd = new FormData(); fd.append("upload", 1); fd.append("upfile", $("#upfile").get(0).files[0]); $.ajax({ url: "/api/Upload", type: "POST", processData: false, contentType: false, data: fd, success: function (d) { console.log(d); } }); }); </script>
后台代码:
using System;
using System.IO;
using System.Web;
using System.Web.Http;
namespace ASP.NET_MVC_study.WepApi
{
public class UploadController : ApiController
{
private string uploadPath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "Upload/";
/// <summary>
/// 上传图片
/// </summary>
/// <returns>成功返回图片URL,失败则返回错误信息</returns>
public string Post()
{
string result = string.Empty;
string imgPath = string.Empty;
HttpRequest request = System.Web.HttpContext.Current.Request;
HttpFileCollection fileCollection = request.Files;
// 判断是否有文件
if (fileCollection.Count > 0)
{
// 获取图片文件
HttpPostedFile httpPostedFile = fileCollection[0];
// 文件扩展名
string fileExtension = Path.GetExtension(httpPostedFile.FileName);
// 图片名称
string fileName = Guid.NewGuid().ToString() + fileExtension;
// 图片上传路径
string filePath = uploadPath + fileName;
// 验证图片格式
if (fileExtension.Contains(".jpg")
|| fileExtension.Contains(".png")
|| fileExtension.Contains(".bmp"))
{
// 如果目录不存在则要先创建
if (!Directory.Exists(uploadPath))
{
Directory.CreateDirectory(uploadPath);
}
// 保存新的图片文件
while (File.Exists(filePath))
{
fileName = Guid.NewGuid().ToString() + fileExtension;
filePath = uploadPath + fileName;
}
httpPostedFile.SaveAs(filePath);
// 把文件的存储路径保存起来
SaveUploadFileInfo(fileName, filePath);
// 返回图片URL
imgPath = Setting.ServerIP + Setting.PhotoPath + fileName;
result = imgPath;
}
else
{
result = "请选择jpg/png/bmp格式的图片";
}
}
else
{
result = "请先选择图片!";
}
return result;
}
}
}