Vue+SSM realizes the preview effect of picture upload

Vue+SSM realizes the preview effect of picture upload

The current requirement is: there is a file upload button. When we click the button, we can select the file to be uploaded, and after confirmation, the picture will be displayed on the interface.

Note: This project uses Vue for the front end, SSM for the back end, Tomcat for the server, and MySQL for the database.

Implementation ideas:

Front-end interface: When the user clicks the upload file button, selects the picture to be uploaded and clicks confirm, the picture data should be transmitted to the backend. When the backend returns the result after processing, the frontend performs subsequent work based on the response result.

Backend: When the backend gets the data sent from the frontend, it saves the image file in a fixed folder (I have thought about this problem for a long time. I think it should be stored on the server. Originally, I stored it in a local folder and then used the path to refer to it. To be honest, this is really stupid. I encountered many problems and spent a long time on it. I cried because of my own stupidity). After the file is saved, the response result is returned. If successful, the relative path of the current image is returned directly, and the front end displays the image according to this path.

The main issue now is how to put the image resources under Tomcat.

To solve this problem, I created a virtual directory under Tomcat, and all the image files, videos and other resources will be placed in this directory folder.

The steps to upload pictures on the backend are as follows:

1. Create a virtual directory under Tomcat

Create a directory named FileDir in the root directory of tomcat (of course this directory can also be created elsewhere)

In tomcat's conf/server.xml, configure the virtual directory. Add the following line
<Context path="/FileDir" docBase="G:\Installation package\Tomcat\Installation package\Tomcat 7.0\FileDir"/>

Add a picture 1.jpg to the virtual directory and start the tomcat test. Visit: http://localhost:8080/FileDir/1.jpg. If you can request pictures, it means the configuration is successful.

2. Backend configuration

Introduce file upload and download jar packages: commons-fileupload-1.3.2.jar and commons-io-1.3.2.jar

Write the SpringMVC configuration file and add the following code:

<!-- Configuring the upload parser -->
 <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
  <!-- Set the request encoding format -->
  <property name="defaultEncoding" value="UTF-8"></property>
</bean>

Create a controller class FileUploadController for file upload

package com.wyf.controller;

import java.io.File;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.wyf.po.Result;
import com.wyf.service.FileServlet;

/**
 * File upload controller * 
 * @author ASUS
 *
 */
@RestController
public class FileUploadController {

 @Autowired
 private FileServlet fileServlet;

 /**
  * Execute image upload* 
  * Solve the problem of Chinese garbled characters when the front-end obtains the back-end data: produces={"application/json; charset=UTF-8"}
  */
 @RequestMapping(value = "/uploadImg", method = RequestMethod.POST, produces = { "application/json; charset=UTF-8" })
 public Result handleUploadImg(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
  // Check if the uploaded file exists if (!file.isEmpty()) {
   // Get the original name of the uploaded file String originalFilename = file.getOriginalFilename();
   //Path to store imagesString rootPath = "G:\\Installation package\\Tomcat\\Installation package\\Tomcat 7.0\\FileDir\\";
   // Set the save directory of uploaded files String path = "\\upload\\images\\applyShop";
   String dirPath = rootPath + path + "\\";
   File filePath = new File(dirPath);
   // If the address where the file is saved does not exist, create the directory first if (!filePath.exists()) {
    filePath.mkdirs();
   }
   // Rename String newFileName = UUID.randomUUID() + "_" + originalFilename;
   try {
    // Use the MultipartFile interface method to upload the file to the specified location file.transferTo(new File(dirPath + newFileName));
   } catch (Exception e) {
    e.printStackTrace();
    return new Result(false, "Upload error");
   }
   // Return relative path String srcPath = path + "\\" + newFileName;
   fileServlet.addUploadFIle(srcPath);
   return new Result(true, srcPath);
  }
  return new Result(false, "file does not exist");
 }
}

A Result class is used here to return data, which is used to encapsulate the returned result information and return it to the front end in JSON format. The code is as follows:

public class Result {

 private boolean flag; //Processing result identifier private String message; //Returned result information /* Omit get() and set()*/
}

The front-end Vue interface sends a request to the backend and obtains the image path by dynamically binding the src attribute.

<template>
  <div class="upload">
    <div class="img-container">
      <!-- Upload preview image -->
      <img :src="src" alt />
    </div>
    <!-- Input for file upload -->
    <form class="input-file" enctype="multipart/form-data" method="post">
      <input type="file" ref="upload" name="uploadImg" id="file" @change="getFile" multiple />
      <!-- label has a for attribute pointing to the unique id of input, so clicking on label is equivalent to clicking on input -->
      <label for="file">Upload image</label>
    </form>
  </div>
</template>
<script>
export default {
  data() {
    return {
     src:require('../../assets/dist/images/admin.jpg'),
     srcPath:''//Relative path of the image};
  },
  methods: {
   getFile(e) {
    let files = e.target.files[0]; //Get uploaded image information let formData = new FormData()
       formData.append('file',files)
      this.$axios.post("/api/uploadImg",formData).then(result=>{
       if(result.data.flag){
            this.srcPath = result.data.message
            this.src = `/imgURL${this.srcPath}`
            }else{
            console.log(result.data.message)
        }
      })
    }
  }
};
</script>

At this point, you can basically upload and preview pictures. But there are bugs and garbled Chinese characters . If the image path contains Chinese characters, the src cannot be parsed. I have been solving this problem for a long time.

I searched various Baidu and finally used the method of modifying the server.xml configuration file of tomcat.
I thought about the reason for the garbled characters. Because my image resources were obtained by accessing tomcat, when the img tag was dynamically bound to the path passed from the background, the submission method was a get request. The Chinese path obtained by the front desk is correct, but it will be garbled under tomcat. The default encoding method of tomcat is iso8859-1 for Chinese encoding, and the encoding method set by the front end is utf-8, so garbled characters appear.

My solution is to modify the tomcat server.xml configuration file

Found in tomcat's server.xml

<Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443"/>

Change this line to

<!--Solve the problem of garbled Chinese characters in the address bar by adding useBodyEncodingForURI="true" URIEncoding="UTF-8" in <Connector -->
<!--useBodyEncodingForURI="true": means get and post requests use the same encoding -->
<!--URIEncoding="UTF-8": request encoding is utf-8 -->
<Connector URIEncoding="UTF-8" connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443" useBodyEncodingForURI="true"/>

The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM.

You may also be interested in:
  • Implementation example of Vue+Element+Springboot image upload
  • Vue+axios sample code for uploading pictures and recognizing faces
  • Problems encountered when uploading images using axios in Vue
  • Vue.js cloud storage realizes image upload function
  • Public multi-type attachment image upload area in Vue page and applicable folding panel (sample code)

<<:  How to make an input text box change length according to its content

>>:  Tomcat8 uses cronolog to split Catalina.Out logs

Recommend

A simple tutorial on how to use the mysql log system

Table of contents Preface 1. Error log 2. Binary ...

JavaScript to show and hide images

JavaScript shows and hides pictures, for your ref...

HTML basic syntax is convenient for those who are just starting to learn HTML

1.1 General marking A general tag consists of an ...

Postman automated interface testing practice

Table of contents Background Description Creating...

Detailed explanation of the problems and solutions caused by floating elements

1. Problem Multiple floating elements cannot expa...

Detailed installation and use tutorial of mysql 8.0.15 under windows

This article shares with you the detailed install...

Summary of coalesce() usage tips in MySQL

Preface Recently, I accidentally discovered MySQL...

Docker connects to a container through a port

Docker container connection 1. Network port mappi...

IE8 Developer Tools Menu Explanation

<br />This article has briefly explained the...

Native JS implements a very good-looking counter

Today I will share with you a good-looking counte...

Solutions to MySql crash and service failure to start

I have been in contact with PHP for so long, but ...