enctype="multipart/form-data"
<form id="uploadForm" enctype="multipart/form-data"> <input id="file" type="file" name="file"/> </form>
說明:
1.監聽input上的change事件能夠實現自動上傳到服務器
2.服務器端經過name
字段,獲取上傳圖片的信息
3.數據信息爲let imginfo = new FormData($('#uploadForm')[0])
,imginfo
是一個對象,經過post('/upload', imginfo);
調用html
<div id="uploadForm"> <input id="file" type="file"/> <button id="upload" type="button">upload</button> </div>
var formData = new FormData(); var imginfo = formData.append('file', $('#file')[0].files[0]); // imginfo經過組裝的方式獲得,經過上面接口實現上傳。 //其中`name=file`和`append('file')`中的file都是服務器端獲取圖片信息的標示。
if (window.FileReader) { var oFileReader = new FileReader(), oFile = e.target.files[0]; if (/^image*/.test(oFile.type)) { oFileReader.onloadend = function (e) { let binfo64 = e.target.result; let postinfo = { image: binfo64, filename: `passport-${new Date().getTime()}` } }; oFileReader.readAsDataURL(oFile); } else { Toast.makeText('傳入圖片文件'); } }
Ajax
上傳圖片信息,並顯示圖片上傳的進度來自https://www.w3ctrain.com/2015/07/11/uploading-image-with-ajax/html5
<form id="fileupload-form"> <input id="fileupload" type="file" name="file" > </form>
//綁定了`submit`事件。 $('#fileupload-form').on('submit',(function(e) { e.preventDefault(); //序列化表單 var serializeData = $(this).serialize(); // var formData = new FormData(this); $(this).ajaxSubmit({ type:'POST', url: *yoururl*, dataType: 'json', data: serializeData, // data: formData, //attention!!! contentType: false, cache: false, processData:false, beforeSubmit: function() { //上傳圖片以前的處理 }, uploadProgress: function (event, position, total, percentComplete){ //在這裏控制進度條 }, success:function(){ }, error:function(data){ alert('上傳圖片出錯'); } }); })); //綁定文件選擇事件,一選擇了圖片,就讓`form`提交。 $("#fileupload").on("change", function() { $(this).parent().submit(); });
說明:
1.使用.serialize()
獲取表單的數據,不一樣經過val
和text
獲取值
2.ajax上傳圖片這三個參數必須配置contentType: false, cache: false, processData:false
3.該處使用了uploadProgress
來獲取文件上傳的進度(本人沒實驗,待測)git