公司業務需求 在上傳檔案功能處實作按住Ctrl實作多選 不多BB直接上代碼
HTML
選擇圖檔:<input type="file" id="descFile" name="descFile" οnchange="fileUpload()" multiple="multiple" />
JS
function fileUpload() {
var files = document.getElementById("descFile").files;
for (var i = 0; i < files.length; i++) {
var file = document.getElementById("descFile").files[i];
var fileName = file.name;
var index = fileName.lastIndexOf('.');
var newName = fileName.substring(0, index);
var fd = new FormData();
fd.append('username', 'root')
fd.append('myfile', file);
$.ajax({
url: '/Home/Upload/?source=' + $("#s_CaseSerial").val() + '&&inOut=OutFile',//位址
type: 'POST',
data: fd,
processData: false, //tell jQuery not to process the data
contentType: false, //tell jQuery not to set contentType
success: function (arg, a1, a2) {
$.modalMsg("操作已完成", "warning");
}
})
}
}
Controller
public ActionResult Upload(string source = "", string inOut = "")
{
HttpPostedFileBase file = Request.Files.Get("myfile");
if (file.ContentLength == 0)
{
return Json(new
{
bRet = false,
sMsg = "請選擇檔案!",
data = ""
}, "text/html");
}
if (file.ContentLength > 52428800)
{
return Json(new
{
bRet = false,
sMsg = "檔案大小不能超過50M!",
path = ""
}, "text/html");
}
//上傳檔案代碼 記得先建立一下 Upload 檔案夾
//var fileName = Path.Combine(Request.MapPath("~/UploadFile"), Path.GetFileName(file.FileName));
//string s_NewFileName = arr_FileName[0] + DateTime.Now.ToString("yyyyMMddHHmmss") + "." + arr_FileName[1];
//string s_FilePath = "Documents\\ClientFile\\" + DateTime.Now.Year + "-" + DateTime.Now.Month + "\\" + s_NewFileName;
string path = "";
string fileName = "";
string returnpath = "";
string extension = Path.GetExtension(file.FileName);
string fname = Path.GetFileNameWithoutExtension(file.FileName);
string newFileName = fname + DateTime.Now.ToString("yyyyMMddHHmmss") + extension;
if (source == "")
{
path = ConfigurationManager.AppSettings["filepath"] + "Documents\\ClientFile\\" + DateTime.Now.Year + "-" + DateTime.Now.Month;
fileName = path + "\\" + newFileName;
returnpath = "Documents\\ClientFile\\" + DateTime.Now.Year + "-" + DateTime.Now.Month + "\\" + newFileName;
}
else
{
path = ConfigurationManager.AppSettings["filepath"] + "Documents\\" + DateTime.Now.Year + "-" + DateTime.Now.Month + "\\" + source.Replace('?', '-') + "\\" + inOut;
fileName = path + "\\" + newFileName;
returnpath = "Documents\\" + DateTime.Now.Year + "-" + DateTime.Now.Month + "\\" + source.Replace('?', '-') + "\\" + inOut + "\\" + newFileName;
}
Directory.CreateDirectory(path);
try
{
file.SaveAs(fileName);
var data = new
{
bRet = true,
sMsg = "上傳成功",
path = returnpath
};
return Content(data.ToJson());
}
catch
{
var data = new
{
bRet = true,
sMsg = "上傳失敗",
path = returnpath
};
return Content(data.ToJson());
}
}
//可以用這種方式擷取上傳的檔案名字
var files = document.getElementById("descFile").files;
var fileName = "";
for (var i = 0; i < files.length; i++) {
var file = document.getElementById("descFile").files[i];
alert(file.name)
}