文章内容
2017/11/4 13:38:20,作 者: 黄兵
文件Ajax上传
实现如下功能:
多文件上传;
后台接收;
Ajax操作,无刷新。
<input type="file" id="Upfile" multiple="multiple" name="Image" onchange="uploadFile()" />
function uploadFile() {
var obj = document.getElementById("Upfile");
var length = obj.files.length;
for (var i = 0; i < length; i++) {
var formData = new FormData();
var name = $("#Upfile").val();
formData.append("file", obj.files[i]);
formData.append("name", obj.files[i].name);
$.ajax({
url: "/Church/UploadChurchPic",
type: "post",
data: formData,
processData: false,
contentType: false,
success: function (responseStr) {
if (responseStr.status === 0) {
console.log("成功" + responseStr);
} else {
console.log("失败");
}
},
error: function (responseStr) {
console.log("error");
}
})
}
}
[HttpPost]
public ActionResult UploadChurchPic(HttpPostedFileBase file)
{
//保存到临时文件夹
string urlPath = "/Resource/Uploads";
string filePathName = string.Empty;
string localPath = Path.Combine(HttpRuntime.AppDomainAppPath, "Resource/Uploads");
if (Request.Files.Count == 0)
{
return Json(new { jsonrpc = 2.0, error = new { code = 102, message = "保存失败" }, id = "id" });
}
string ex = Path.GetExtension(file.FileName);
filePathName = Guid.NewGuid().ToString("N") + ex;
if (!System.IO.Directory.Exists(localPath))
{
System.IO.Directory.CreateDirectory(localPath);
}
file.SaveAs(Path.Combine(localPath, filePathName));
return Json(new
{
status = 0,
filePath = urlPath + "/" + filePathName//返回一个视图界面可直接使用的url
});
}
评论列表