jquery ajax file upload NET MVC 無重新整理檔案上傳

jay-lee發表於2018-04-08

網上有各種各樣的檔案上傳方法,有基於JS框架的、也有基於flash swf外掛的。

這次分享一個比較簡單而且實用能快速上手的檔案上傳方法,主要步驟:

1.引用Jquery包,我用的是jquery-1.11.3.min.js 版本

2.編寫JS程式碼

3.HTML中增加type=file控制元件

程式碼如下:

HTML程式碼:

    <form id="fileupload" method="post"  enctype = "multipart/form-data">
         <input type="file" id="fileid" name="fileid" accept="application/vnd.ms-excel">
     <input type="button" id="confirmuploadid" value="上傳" />
</form>
//JS實現

   $(`#confirmuploadid`).on(`click`, function () {
    uploadProduct();

   });

function uploadProduct() {
    var formid = $("#fileupload");
     var fd = new FormData(formid[0]);  //form表單的方式例項化一個formData
    fd.append(`file`, $(`#fileid`)[0].files);
    fd.append(`userid`, userid);
    $.ajax({
        url: `File/Setting`,
        type: `POST`,
        dataType: `JSON`,
        data: fd,
        async: false,
        cache: false,
        contentType: false,
        processData: false,
        beforeSend: function () {
            $("#confirmuploadid").prop("disabled", true);
        },
        success: function (returndata) {
           $("#confirmuploadid").prop("disabled", false);
            alert(returndata.Message);
        },
        error: function (returndata) {
            alert("上傳失敗,請檢查資料正確性,如:有些數字輸入項,是否輸入了字元!");
        }
    });
}        
 
//MVC實現
public class FileController : Controller { [HttpPost] public ActionResult Setting() { string userid = "1"; string username = "1"; FunctionBackMessage functionBackMessage = new FunctionBackMessage(); functionBackMessage.IsSuccess = false; functionBackMessage.Message="上傳失敗,稍後重試!"; if (!string.IsNullOrEmpty(username)) { HttpFileCollectionBase files = Request.Files; string _urlstr = Request.Url.AbsoluteUri; FunctionBackMessage fc = new FunctionBackMessage(); fc.IsSuccess = true; fc.Message = "上傳成功"; if (files.AllKeys.Length > 0) { for (int i = 0; i < files.AllKeys.Length; i++) { var myFile = files[i]; double myFileLength = myFile.ContentLength / 1024.0 / 1024.0; int InputMediaExcelLength = !string.IsNullOrEmpty(Global.GetAppString("InputMediaExcelLength")) ? int.Parse(Global.GetAppString("InputMediaExcelLength")) : 50; if (myFileLength > InputMediaExcelLength)//超出指定大小 { fc.IsSuccess = false; fc.Message = "為了保證資料處理效率,每次上傳檔案小於" + InputMediaExcelLength + "M,如超出請拆分記錄分多次上傳!"; } else { // string projectId = context.Request["projectId"]; // string username = context.Request["username"]; if ((!Path.GetExtension(myFile.FileName).Contains("xls") && !Path.GetExtension(myFile.FileName).Contains("xlsx"))) { functionBackMessage.IsSuccess = false; functionBackMessage.Message = "請上傳Excel格式檔案!"; return Json(functionBackMessage, "application/json"); } //檔案儲存 string uploadPath = HttpContext.Current.Server.MapPath("/tempfile") + "\";//伺服器臨時路徑(不含檔名和字尾) if (!Directory.Exists(uploadPath)) { Directory.CreateDirectory(uploadPath); } string fileName = DateTime.Now.Ticks + "_" + myFile.FileName; string fileFull = uploadPath + fileName;//檔案路徑,包含檔名和字尾 try { myFile.SaveAs(fileFull);//儲存檔案 } catch (Exception ex) { com.log.Loger.Debug("uploadMediaSource 儲存檔案失敗", ex); } } } } else { functionBackMessage.IsSuccess = false; functionBackMessage.Message = "沒有獲取到上傳檔案"; } } return Json(functionBackMessage, "application/json"); } }

 

相關文章