先引用 ajaxfileupload.js 沒有自己去csdn下
接下來是HTML
<input type="file" id="file1" name="file" style="display: none" accept="image/x-png,image/gif,image/jpeg,image/bmp" multiple="multiple" />
<button type="button" class="btn btn-info" id="btnFile"><i class="fa fa-cloud-upload"> 上傳</i></button>
其中 accept 可以指定上傳格式 multiple="multiple" 此屬性可進行多文件選擇
<a class="btn btn-success btn-sm" href="@fjTable.Rows[a]["LJ"]" target="_blank" title="下載" ><i class="fa fa-cloud-download"></i> 查看</a> target="_blank" 打開新窗體下載 target還有其他幾個屬性這里就不多說了
JS部分
$("#btnFile").click(function () {
$("#file1").click();
})
$("#file1").change(function () {
if ($("#file1").val().length > 0) {
ajaxFileUpload();
}
else {
swal({ title: '請選擇上傳文件!', text: '', type: 'info' });
}
});
function ajaxFileUpload() {
$.ajaxFileUpload
(
{
url: '/FinancialReimbursement/FinancialReimbursement/Upload', //用於文件上傳的服務器端請求地址
type: 'post',
data: { Id: '123', name: 'add' }, //此參數非常嚴謹,寫錯一個引號都不行
secureuri: false, //是否需要安全協議,一般設置為false
fileElementId: 'file1', //文件上傳域的ID
dataType: 'json', //返回值類型 一般設置為json
success: function (data, status) //服務器成功響應處理函數
{
alert("上傳成功");
},
error: function (data, status, e)//服務器響應失敗處理函數
{
alert(e);
}
}
)
后台部分
public ActionResult Upload()
{
NameValueCollection nvc = System.Web.HttpContext.Current.Request.Form;
string type = nvc.Get("name");//獲取參數
HttpFileCollection hfc = System.Web.HttpContext.Current.Request.Files;
if (hfc.Count > 0 )
{
#region 執行多個文件上傳
for (int i = 0; i < hfc.Count; i++)
{
var FileNameArr = hfc[i].FileName.Split('.');
string FileName = DateTime.Now.ToString("yyyyMMddhhmmss") + "_" + FileNameArr[0] + "." + FileNameArr[1];
imgPath += "/AllFileUp/ForTheAttachment/" + FileName + ",";
string imgP = "/AllFileUp/ForTheAttachment/" + FileName;
string PhysicalPath = Server.MapPath(imgP);
if (!Directory.Exists(Server.MapPath("/AllFileUp/ForTheAttachment")))//存放路徑文件夾不存在就自動新建
{
Directory.CreateDirectory(Server.MapPath("/AllFileUp/ForTheAttachment"));
}
hfc[i].SaveAs(PhysicalPath);
}
#endregion
}
return Json(new { count = hfc.Count});//返回保存文件的個數
}
寫的很亂 第一次寫 一點格式都沒有 哈哈哈