1. 使用jquery.form.js實現文件上傳及進度條前端代碼
ajax的表單提交只能提交data數據到後台,沒法實現file文件的上傳還有展示進度功能,這里用到form.js的插件來實現,搭配css樣式簡單易上手,而且高大上,推薦使用。
需要解釋下我的結構, #upload-input-file 的input標簽是真實的文件上傳按鈕,包裹form標簽後可以實現上傳功能, #upload-input-btn 的button標簽是展示給用戶的按鈕,因為需要樣式的美化。上傳完成生成的文件名將會顯示在 .upload-file-result 裡面, .progress 是進度條的位置,先讓他隱藏加上 hidden 的class, .progress-bar 是進度條的主體, .progress-bar-status 是進度條的文本提醒。
去掉hidden的class,看到的效果是這樣的
[圖片上傳失敗...(image-2c700a-1548557865446)]
將上傳事件綁定在file的input裡面,綁定方式就隨意了。
var progress = $(".progress-bar"), status = $(".progress-bar-status"), percentVal = '0%'; //上傳步驟 $("#myupload").ajaxSubmit({ url: uploadUrl, type: "POST", dataType: 'json', beforeSend: function () { $(".progress").removeClass("hidden"); progress.width(percentVal); status.html(percentVal); }, uploadProgress: function (event, position, total, percentComplete) { percentVal = percentComplete + '%'; progress.width(percentVal); status.html(percentVal); console.log(percentVal, position, total); }, success: function (result) { percentVal = '100%'; progress.width(percentVal); status.html(percentVal); //獲取上傳文件信息 uploadFileResult.push(result); // console.log(uploadFileResult); $(".upload-file-result").html(result.name); $("#upload-input-file").val(''); }, error: function (XMLHttpRequest, textStatus, errorThrown) { console.log(errorThrown); $(".upload-file-result").empty(); } });
[圖片上傳失敗...(image-3d6ae0-1548557865446)]
[圖片上傳失敗...(image-9f0adf-1548557865446)]
更多用法可以 參考官網
2. ajax怎麼提交帶文件上傳表單
上傳的文件是沒有辦法和表單內容一起非同步的,可考慮使用jquery的ajaxfileupload,或是其他的插件,非同步上傳文件後,然後再對表單進行操作。
3. ajax怎樣提交form表單與實現文件上傳
Ajax 提交form方式可以來將form表單序列化源 然後將數據通過data提交至後台,例如: