//-----前端文件-------
form id="uploadForm" enctype="multipart/form-data">
<input id="files" type="file" multiple="multiple" onchange="onChange();"/>
<div id="div1" style="width:100px;height:auto"></div>
<div id="flshID"></div>
<button id="upload" type="button">上传</button>
<button id="swfupload" type="button" onclick="swfUp();">swf上传</button>
<div id="picloding"></div>
<div id="addimgs"></div>
</form>
//----------------js------------------------------------
$(function () {
$("#upload").click(function () {
var formdata = new FormData();
var wenjian = $("#files")[0].files// document.getElementById("files").files;这里$("#files")[0]是jquery对象装换成dom对象
if (wenjian.length <= 0) {
alert("请选择文件");
retun;
}
for (i = 0; i < wenjian.length; i++) {
formdata.append(wenjian[i].name, wenjian[i]);
}
$.ajax({
type: "POST",
url: "/My/UploadFiles",
data: formdata,
datatype: "json",
contentType: false,//必须false才会自动加上正确的Content-Type
processData: false,//必须false才会避开jQuery对 formdata 的默认处理 ,XMLHttpRequest会对 formdata 进行正确的处理
success: function (result) {
alert(result.msg);
},
error: function () {
alert("Error");
}
});
});
});
//后端 controller
public JsonResult UploadFiles()
{
var files = Request.Files;
for (int i = 0; i < files.Count; i++)
{
string key=files.Keys[i];
var file=files[key];
string fileName = file.FileName;
var filesUrl = Server.MapPath("~/Upload");
if (Directory.Exists(filesUrl) == false)//路径不存在则创建
{ Directory.CreateDirectory(filesUrl); }
var path = Path.Combine(filesUrl, fileName);
if (System.IO.File.Exists(path))
{
return Json(new {msg="已存在同名文件" });
}
file.SaveAs(path);
}
return Json(new { msg = "上传成功" });
}