vue+springboot save Avatar

Posted by SevereSoldier on Tue, 01 Mar 2022 06:39:50 +0100

Process: the front end sends the avatar, the back end receives it, and then creates the avatar under the class path of the project, then puts the address of the avatar into the database, updates the user's Avatar, and then returns the user information. The front end receives the user information, obtains the avatar address, and accesses the avatar saved in the project, but there are security problems, I planned to upload to the drawing bed before, but due to the ability problem, I kept making mistakes. Finally, I decided to save the picture to the project.

design sketch:

 

vue uses a third-party component, vue image clip upload

Step 1: install in the front-end vue project

npm install vue-image-crop-upload

npm install –save-dev babel-polyfill

Step 2: use this component

<div>
      <my-upload
      :params="params"//Carry the parameters passed to the back-end. How to receive the back-end code
      :modelValue.sync="imagecropperShow"//If you don't write like this, you will click close but can't close it
      :key="imagecropperKey" //Never mind
      :width="300" //Never mind
      :height="300" //Never mind
      lang-type="zh" //zh is Chinese and en is English
      img-format="png" //Format of pictures passed to the back end
      :noRotate='false' //Never mind
      @crop-success="cropSuccess" //Callback function for image clipping
      @crop-upload-success="cropUploadSuccess"//Callback function for successful upload
      @crop-upload-fail="cropUploadFail" //Callback function for upload failure
      url="/api/uploadAvatar"//Address to access the backend
      ></my-upload>
</div>

Step 3: js code

 

<script>
  import 'babel-polyfill'; // es6 shim introduction
  import myUpload from 'vue-image-crop-upload';//Introduction component
  export default {
    components: {
      'my-upload': myUpload
    },
    data() {
      return {
        params:{
          cid:this.$cookies.get('cid')//The parameters sent to the back-end can be deleted without carrying according to the demand
        },
        imagecropperShow: false,
        imagecropperKey: 0
      }
    },
    methods: {
      cropSuccess(imgDataUrl, field) {
        console.log('-------- crop success --------');
        console.log(imgDataUrl);
        this.avatar=imgDataUrl;
        console.log(field);
      },
      //Upload success callback
      cropUploadSuccess(res, originPicName) {//res is the result returned by the backend, and originPicName is the name of the picture received by the backend
        console.log('-------- upload success --------');
        console.log(res);
        console.log(originPicName);
      },
      //Upload failure callback
      cropUploadFail(status, field) {
        console.log('-------- upload fail --------');
        console.log('Upload failure status' + status);
        console.log('field: ' + field);

      }
    }
  }
</script>

 

Please read this text with the following code! Easy to understand

Spring boot code, CID is the parameter in the front-end param, files Get ("Avatar") seems to be due to the use of this third-party component, which makes the transmitted pictures seem to become avatar PNG format. I'm not sure. If there is a problem in the direct copy operation, you can debug it to see what the name of the received file is, and then change avatar to yours. ApiResult is my return value. You can directly set it to void, and return is not required. First see whether it is successful, and then save the picture in the corresponding position of the project, Note: the absolute path of the project should not have Chinese!!! Otherwise, a new folder will be created. The Chinese name is a mess of English, and then the pictures of the project will not be accessed through the browser. The code in try studentservice changeImg(cid, img);
Student student = studentService.findById(cid);

I want to save the picture address in the project to the database, and then find out the modified students and return them to the front end. When referring, I can first see whether the picture is successfully saved, and then consider the address of the picture added to the database

@Autowired
    ServerConfig serverConfig;

@PostMapping("/uploadAvatar")
    public ApiResult uploadAvatar(long cid, MultipartHttpServletRequest multipartHttpServletRequest, HttpServletRequest request) throws IOException {
        //Get file map object
        Map<String, MultipartFile> files = multipartHttpServletRequest.getFileMap();
//        Get picture file
        MultipartFile file = files.get("avatar");
//        Get the absolute / static student number of the project
        String path = ResourceUtils.getURL("classpath:").getPath() + "static/headImage/students/"+cid+"/";
//        Get the root path of the project + / headImage /, i.e. / headImage //
        String url = request.getContextPath() + "/headImage/students/"+cid+"/";
//        Create a file
        File filePath = new File(path);
        System.out.println("Save path of file:" + path);
        if (!filePath.exists() && !filePath.isDirectory()) {
            System.out.println("Directory does not exist, create directory:" + filePath);
            filePath.mkdirs(); // mkdir() does not create a directory, and returns false when the corresponding path cannot be found; mkdirs() creates a corresponding directory when the directory does not exist
        }
        //Get the original file name (including format)
        String originalFileName = file.getOriginalFilename();
        //Get the file type with the last `` Identify png for
        String type = originalFileName.substring(originalFileName.lastIndexOf(".") + 1);
        // New file name, which can be renamed as needed
        String fileName = cid+"_"+ SaltUtil.getSalt(8)+ "."+ type;
        //Create a file in the specified path
        File targetFile = new File(path, fileName); // OutputStream. Is not used When writing (), it is a File object, which is saved in memory and cannot be seen in the hard disk, but this object can be used
        try {
            // Use the transferTo method of spring MVC to upload files
            file.transferTo(targetFile);
//            http://192.168.220.1:8080 +
            String HostAndPortUrl=serverConfig.getUrl();
//            Get the host and port number of the project 192.168.220.1:8080 +/headImage / student number / + picture name
            String img=HostAndPortUrl+ url + fileName;
            System.out.println(img);
            studentService.changeImg(cid, img);
            Student student = studentService.findById(cid);
            return ApiResultHandler.buildApiResult(200,"Avatar uploaded to local successfully",student);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ApiResultHandler.buildApiResult(400,"Failed to upload avatar to local",null);
    }

SaltUtil class is used to obtain the random code, so that each picture has a different name

public class SaltUtil {
    public static String getSalt(int n){
        char[] chars="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890".toCharArray();
        StringBuilder sb=new StringBuilder();
        for (int i = 0; i < n; i++) {
            char aChar = chars[new Random().nextInt(chars.length)];
            sb.append(aChar);
        }
        return  sb.toString();
    }

    public static void main(String[] args) {
        String salt = getSalt(8);
        System.out.println(salt);
    }
}

The ServerConfig class is used to obtain the host and port number of the current project

@Component
public class ServerConfig implements ApplicationListener<WebServerInitializedEvent> {
    private int serverPort;

    public String getUrl() {
        InetAddress address = null;
        try {
//            192.168.220.1
            address = InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return "http://"+address.getHostAddress() +":"+this.serverPort;
    }

    @Override
    public void onApplicationEvent(WebServerInitializedEvent event) {
        this.serverPort = event.getWebServer().getPort();
    }

}

If you have any questions, you can comment or contact by private letter. I believe your ability should be able to successfully complete this simple function. Finally, the security of this function is very low, because the returned image address is the address of the back-end project. If it is only a simple completion function, you can refer to it.

 

Topics: Front-end Spring Boot Vue.js