This article introduces to you a summary (code) of various methods of file uploading on the front end. It has a good reference value and I hope it can help friends in need.
HTML enctype attribute is essential
<form action="http://localhost:8081/thingsparse/addorupdthingsparse" method="post" enctype="multipart/form-data"> <input type="file" name="file" value="选择上传文件..."/> <input id="submit_form" type="submit" class="btn btn-success save" value="保存"/> </form>
HTML multi-file upload
JS
(function(){ $('#upload').change(function(e){ let files = e.target.files; let params = new FormData(); for(let i = 0; i < files.length; i++){ //visit_file就是后台用来接受的字段,因为是一个数组,所以加一个[] params.append('visit_file[]', files[i], files[i].name); } $.ajax({ type: 'post', url: "http://192.168.1.101:8080/springbootdemo/file/upload", data: params, processData: false,//必不可少属性 traditional: true,//必不可少属性 contentType: false,//必不可少的属性 }).success(function (data) { console.log(data); }).error(function () { console.log("上传失败"); }) })()
This method solves the problem of page jump after uploading files, but what if the image you upload is very large? Next is an optimization solution we are going to talk about when uploading larger files. Nowadays, in order to improve the user experience, we not only provide users with the ultimate experience when browsing, but also do not feel the lag when uploading. This cannot be done by the back end and can only be left to the front end. Below we introduce this optimization scheme.
HTML multi-file upload
JS
(function(){ $('#upload').change(function(e){ let files = e.target.files; let params = new FormData(); for(let i = 0; i < files.length; i++){ //visit_file就是后台用来接受的字段,因为是一个数组,所以加一个[] params.append('visit_file[]', files[i], files[i].name); } //图片预览地址数组 let previewArr = previewImage(files); for(let i = 0 ; i < previewArr.length; i++){ } } //上传图片 压缩过的二进制文件只能单张上传处理,我试过多上同时上传失败了,你们也可以试试,也许可以找到方法 function uploadImage(params){ $.ajax({ type: 'post', url: "http://192.168.1.101:8080/springbootdemo/file/upload", data: params, processData: false,//必不可少属性 traditional: true,//必不可少属性 contentType: false,//必不可少的属性 }).success(function (data) { console.log(data); }).error(function () { console.log("上传失败"); }) } //图片预览 function previewImage(files){ let previewsArr = []; for(let i = 0; i < files.length; i++){ let fileReader = new FileReader(); fileReader.readAsDataURL(files[i]); fileReader.onloaded = () => { //数组放入获取的base64本地图片地址 previewsArr.push(fileReader.result); } } return previewsArr; } //图片压缩 function compressImage(base64URL){ let img = new Image(); let canvas = document.createElement('canvas'); let context = canvas.getContext('2d'); img.src = base64URL; img.onload = () => { // 图片原始尺寸 var originWidth = img.width; var originHeight = img.height; // 最大尺寸限制 let maxWidth = 400, maxHeight = 400; // 目标尺寸 let targetWidth = originWidth, targetHeight = originHeight; // 图片尺寸超过400x400的限制 if (originWidth > maxWidth || originHeight > maxHeight) { if (originWidth/originHeight > maxWidth/maxHeight) { //更宽,按照宽度限定尺寸 targetWidth = maxWidth; targetHeight = Math.round(maxWidth * (originHeight / originWidth)); }else{ targetHeight = maxHeight; targetWidth = Math.round(maxHeight * (originWidth / originHeight)); } } // canvas对图片进行缩放 canvas.width = targetWidth; canvas.height = targetHeight; // 清除画布 context.clearRect(0, 0, targetWidth, targetHeight); // 图片压缩 context.drawImage(img, 0, 0, targetWidth, targetHeight); //canvas直接转blob二进制文件,但是大部分浏览器不支持 // canvas.toBlob(function (blob) { // console.log(blob) // resolve(blob) // }, 'image/png'); let base64Data = canvas.toDataURL("image/png", 0.92); let blob = dataURItoBlob(base64Data); //上传图片 let params = new FormaData(); params.append('visit_file', blob, 'cavas.png'); uploadImage(params); } } /** * base64 转二进制文件 * @param {*} base64Data */ function dataURItoBlob(base64Data) { var bytes = window.atob(base64Data.split(',')[1]); //去掉url的头,并转换为byte //处理异常,将ascii码小于0的转换为大于0 var ab = new ArrayBuffer(bytes.length); var ia = new Uint8Array(ab); for (var i = 0; i < bytes.length; i++) { ia[i] = bytes.charCodeAt(i); } return new Blob([ab], { type: 'image/png' }); } })()
The page style, image compression and preview here are the same as above, here I mainly configure the http of axois so that the post interface can upload successfully.
/** * * @param {路由} url * @param {路由参数} params * @param {文件数据} body */ upload(url, params = '', body = {}) { let path = config.host + url + params; // console.log(body); return axios({ method: "POST", url: path, data: body, processData: false, //必不可少参数 traditional: true, //比不可少参数 contentType: false,//比不可少参数 headers: { 'token': localStorage['token'], 'originno': config.originno, "Content-Type": false } }).then( res => res ).catch((error) => { console.log(error); }) }
I also encountered a need recently when I was working on a project. I was using vue axois at the time. How to submit and report errors. In the end, I found that the file was not transferred. As long as the three configurations are essential parameters, the upload can be successful. If you want users to have a better experience, you can compress and preview the images locally.
Related recommendations:
How to use php and layui to implement the code of uploading and previewing images
How to implement php Code for compressing images in equal proportions
The above is the detailed content of Summary of various methods for file upload on the front end (code). For more information, please follow other related articles on the PHP Chinese website!