Summary of various methods for file upload on the front end (code)

不言
Release: 2018-07-28 10:45:04
Original
10688 people have browsed it

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.

1. Submit upload through Form form

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>
Copy after login

The above method uses the form’s own attributes Submitting seems simple, but it also has its biggest disadvantage, which is that it jumps directly after the submission is completed, which cannot meet the vast majority of current needs. Then I will introduce another way to directly use xaj's post method and FormData to upload files.

2. Upload via jQuery post request

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("上传失败");
        })
    })()
Copy after login

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.

3. Local preview, Canvas image compression, convert blob binary file

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(&#39;visit_file[]&#39;, files[i], files[i].name);
            }
            //图片预览地址数组
            let previewArr = previewImage(files);   
            
            for(let i = 0 ; i < previewArr.length; i++){
                
            }   
        }
        
        //上传图片  压缩过的二进制文件只能单张上传处理,我试过多上同时上传失败了,你们也可以试试,也许可以找到方法
        function uploadImage(params){
                $.ajax({
                type: &#39;post&#39;,
                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: &#39;image/png&#39;
            });
          }
        
    })()
Copy after login

Here, the local base64 file is obtained through FileReader, and then the image is compressed through canvas, and finally converted into a binary blob file and transmitted to the server. What can be done better here is to use promises to return the compression function without having to call and upload within the compression function to reduce coupling. For everyone’s understanding, I will not separate them here. Haha~~ Mainly because I find it troublesome...

4. Upload images to Vue axios

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 = &#39;&#39;, 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: {
            &#39;token&#39;: localStorage[&#39;token&#39;],
            &#39;originno&#39;: config.originno,
            "Content-Type": false
          }
        }).then(
          res => res
        ).catch((error) => {
          console.log(error);
        })
      }
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template