Detailed use of vue-upload to upload pictures (document server)

foreword

  • In actual development, our pictures, files, and PDFs should all be stored in the document server. Thereby optimizing the code and reducing the code file size.

  • We can let the backend build the document server, write the corresponding storage interface api, and we can use the Upload component to upload.

  • But what we need to pay attention to is that in actual development. The token and userid (user id) set in the request interception need to be reset once.

  • Because we use the upload component to upload directly, without passing through axios, it cannot be intercepted. To set 2 parameters in headers (request header)

  • Remember that it needs to be configured in Nginx, and there may be an online document server post request to upload a file 413 (request body is too large - detailed error report home page article)

Code

1. Use the upload component in the add form (are you hungry)

<el-form-item label="维保打印记录:" prop="fileList">
            <!-- <el-input v-model="form.mcRecord" style="width: 350px"></el-input> -->
            <!-- list-type="picture" 上传图片的样式 -->
            <el-upload
              class="upload-demo"
              :action="upload.url"
              :on-preview="handlePreview"
              :headers="upload.headers"
              :on-remove="handleRemove"
              :on-success="handleFileSuccess"
              :file-list="fileList"
              list-type="picture"
              :limit="10"
              :on-exceed="handleExceed"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件,且不超过500kb
              </div>
            </el-upload>
</el-form-item>

2. Set parameters in data

2.1 fileList is the place where the uploaded pictures are stored. It is an array object. I directly convert it into an array string and store it in the backend.

2.2url is the backend address of the current connection plus the api address

2.3 headers is the upload attribute, add the token and tenant-id (user id) in the api request header to verify the identity.

2.4 getToken and getTenantId are methods in utils to obtain token and user id.

// 上传图片成功之后存储地方
      fileList: [],
      // 图片上传地址,和请求头数据
      upload: {
        // 设置上传的请求头部
        headers: { token: getToken(), "tenant-id": getTenantId() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/media/upload/coursefile",
      },

3. Methods in methods

For the convenience of viewing, when you click on a file that has been successfully uploaded, it will dynamically use js to create an img in the document to display the image for easy viewing.

// 文件上传成功钩子
    handleFileSuccess(response, file, fileList) {
      console.log("response", response);
      console.log("file", file);
      console.log("fileList", fileList);
      let x = {};
      x.name = response.filename;
      x.url = response.url;
      x.id = response.id;
      console.log("上传图片", x);
      this.fileList.push(x);
    },
    // 点击已上传文件右上角删除钩子
    handleRemove(file, fileList) {
      // console.log("id", file.id);
      console.log("删除之后", fileList);
      // const x = this.fileList.findIndex((v) => v.id == file.id);
      // console.log("删除下标", x);
      // this.fileList.splice(x, 1);
      this.fileList = fileList;
      console.log("处理过数据", this.fileList);
    },
    // 文件上传数量超过设置数量
    handleExceed(files, fileList) {
      this.$message.warning(`最多只能选择10张图片${fileList.length} 个文件`);
    },
    // 点击文件列表中已上传的文件时的钩子
    handlePreview(file) {
      console.log(file);
      const image = new Image();
      image.src = file.url;
      image.onload = () => {
        // 创建弹出层
        console.log("执行了");
        const previewContainer = document.createElement("div");
        previewContainer.style.position = "fixed";
        previewContainer.style.top = 0;
        previewContainer.style.bottom = 0;
        previewContainer.style.left = 0;
        previewContainer.style.right = 0;
        previewContainer.style.zIndex = 99999;
        previewContainer.style.backgroundColor = "rgba(0,0,0,0.8)";
        previewContainer.style.display = "flex";
        previewContainer.style.justifyContent = "center";
        previewContainer.style.alignItems = "center";
        document.body.appendChild(previewContainer);
        // 在弹出层中添加图片
        const previewImage = document.createElement("img");
        previewImage.src = file.url;
        previewImage.style.maxWidth = "80%";
        previewImage.style.maxHeight = "80%";
        previewContainer.appendChild(previewImage);
        // 点击弹出层,关闭预览
        previewContainer.addEventListener("click", () => {
          document.body.removeChild(previewContainer);
        });
      };
    },

4. Configuration in Nginx - prevent the upload interface from reporting 413 errors (the request body is too large) - there are articles on the home page

Add a configuration file under http in the nginx/conf/nginx file

worker_processes  1;
events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
    
    #解决请求体过大配置
    #允许客户端请求的最大单文件字节数
    client_max_body_size 15m; 
    #缓冲区代理缓冲用户端请求的最大字节数
    client_body_buffer_size 128k;

    server {
        listen       80;
        #定义服务器的默认网站根目录位置
        server_name  localhost;
        location / {
            root   html/dist;
            index  index.html index.htm;
            try_files $uri $uri/ /index.html; #解决页面刷新404问题
        }
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
}

Notice:

Direct copying needs to change the url (api interface path) according to the actual situation, the parameters carried in the request header in headers (subject to the request.js file), and configure in Nginx, otherwise there will be 413 request body too large - the homepage article has


Summarize:

After this process, I believe you have a preliminary deep impression on the detailed use of vue-upload to upload pictures (document server), but the situation we encounter in actual development is definitely different, so we need to understand it. The principle remains the same. Come on, hit the workers!

Please point out any deficiencies, thank you -- Fengguowuhen

Guess you like

Origin blog.csdn.net/weixin_53579656/article/details/130713703