Spring boot + Vue file upload, how to carry token information?

Time:2020-9-23

@[toc]
SongGe has also written several articles and even videos on file upload

  • Spring boot + Vue + fastdfs to achieve front and back end separation file upload

However, the scheme mentioned before and with the partners is based on the session for authentication, so it is not necessary to consider the issue of carrying a token. However, in the separate development of the front end and the back end, we may adopt JWT or oauth2 + JWT method for authentication. If this is the case, we will have to pass the token manually.

Today, let’s talk about the manual token passing.

1. Traditional scheme

Let’s first see how to upload files based on session authentication.

In Vue.js If Axios is used for network requests and the elementui library is used, generally speaking, there are two different implementation schemes for file upload

  1. Upload files through Ajax
  2. Upload files through the upload component in elementui

Each has its own advantages and disadvantages. Let’s look at it separately.

1.1 preparation

First of all, we need to do a little bit of preparation, which is to provide a file upload interface on the back end. This is a common spring boot project, as follows:

SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");
@PostMapping("/import")
public RespBean importData(MultipartFile file, HttpServletRequest req) throws IOException {
    String format = sdf.format(new Date());
    String realPath = req.getServletContext().getRealPath("/upload") + format;
    File folder = new File(realPath);
    if (!folder.exists()) {
        folder.mkdirs();
    }
    String oldName = file.getOriginalFilename();
    String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."));
    file.transferTo(new File(folder,newName));
    String url = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + "/upload" + format + newName;
    System.out.println(url);
    return  RespBean.ok ("upload succeeded!");
}

Here the file upload is relatively simple, the uploaded file is classified according to the date, and the UUID is used to rename the file.

Here, in order to simplify the code, I omit the exception capture. The upload result directly returns success. The back-end code can be modified according to the actual situation.

This is for convenience. I directly store the files locally. My partners can also upload files more professionally in combination with fastdfs. You can refer to SongGe’s article: spring boot + Vue + fastdfs to realize front-end and back-end separation of file upload.

1.2 Ajax upload

In Vue, file upload is realized by Ajax. The scheme is basically the same as that of traditional Ajax. The only difference is the way to find elements.

<input type="file" ref="myfile">
< El button @ Click = "importdata" type = "success" size = "mini" icon = "El icon-upload2" > import data < / El button >

Here, we first provide a file import input component, and then an import button to complete the import logic in the event of the import button.

importData() {
  let myfile = this.$refs.myfile;
  let files = myfile.files;
  let file = files[0];
  var formData = new FormData();
  formData.append("file", file);
  this.uploadFileRequest("/system/basic/jl/import",formData).then(resp=>{
    if (resp) {
      console.log(resp);
    }
  })
}

The core logic of this upload is explained as follows:

  1. First of all, use the $refs in Vue to find the element where the file is stored.
  2. There is a files array inside the input element of type file, in which all selected files are stored. Since multiple files can be selected during file upload, the files object obtained here is an array.
  3. From the files object, get the file you want to upload. Since this is a single choice, it is actually the first item in the array.
  4. Construct a formdata to store the uploaded data. Formdata cannot be configured in chain like StringBuffer in Java.
  5. After the fromdata is constructed, the data can be uploaded directly. Formdata is the data to be uploaded.
  6. Two points should be paid attention to when uploading files: 1. The request method is post; 2. SettingContent-Typebymultipart/form-data

As like as two peas, the way to upload files is actually the traditional Ajax uploading file. Unlike the common jQuery, the way of finding elements is different. (in fact, the element search can also be implemented in the original way in JavaScript). This is a generic approach, regardless of which front-end framework to use. Finally, let’s take a look at the package upload method:

export const uploadFileRequest = (url, params) => {
  return axios({
    method: 'post',
    url: `${base}${url}`,
    data: params,
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  });
}

After these steps of configuration, even if the front-end upload is completed, the file can be uploaded.

1.3 using the El upload component

If you use El upload, you need to introduce elementui. Therefore, it is generally recommended that if you use elementui as a UI control, you can consider using El upload components to upload files. If you do not use elementui, it is not recommended to use El upload components. As for other UIs, it is not recommended to use El upload components Control, each has its own file upload components, specific use can refer to their own documents.

<el-upload
  style="display: inline"
  :show-file-list="false"
  :on-success="onSuccess"
  :on-error="onError"
  :before-upload="beforeUpload"
  action="/system/basic/jl/import">
  <el-button size="mini" type="success" :disabled="!enabledUploadBtn" :icon="uploadBtnIcon">{{btnText}}</el-button>
</el-upload>
  1. Show file list indicates whether to display the list of uploaded files. The default value is true. It is set to not display here.
  2. Before upload means the callback before upload. In this method, you can do some preparatory work, such as showing a progress bar to the user.
  3. On success and on error indicate the callback when the upload is successful and failed respectively. In these two methods, a corresponding prompt can be given to the user. If there is a progress bar, the progress bar needs to be closed in these two methods.
  4. Action refers to the file upload address.
  5. The click status and icon of the upload button are set as variables. During the file upload process, the click status of the upload button is changed to non clickable, and the icon is modified to an icon loading.
  6. The uploaded text is also set as a variable. By default, the uploaded button text isData importWhen the upload is started, change the text on the button toImporting

The corresponding callbacks are as follows:

onSuccess(response, file, fileList) {
  this.enabledUploadBtn = true;
  this.uploadBtnIcon = 'el-icon-upload2';
  this.btnText  ='data import ';
},
onError(err, file, fileList) {
  this.enabledUploadBtn = true;
  this.uploadBtnIcon = 'el-icon-upload2';
  this.btnText  ='data import ';
},
beforeUpload(file) {
  this.enabledUploadBtn = false;
  this.uploadBtnIcon = 'el-icon-loading';
  this.btnText  ='importing';
}
  1. When the file starts to upload, modify the upload button to be non clickable, and modify the icon and text of the upload button.
  2. When the file upload is successful or failed, modify the status of the upload button to clickable, and restore the icon and text of the upload button.

The upload effect picture is as follows:

Spring boot + Vue file upload, how to carry token information?

Use El upload to upload files. SongGe has recorded a video before. For your reference (this video excerpt is from Song GE’s self-made spring boot + Vue + micro personnel series video tutorial)

<! — Video location — >

1.4 comparison of the two methods

The two upload methods have their own advantages and disadvantages

  1. The biggest advantage of the first method is that it can be used everywhere. However, the monitoring of the upload process and the display of the progress bar need to be realized by ourselves.
  2. The second method is not universal because it is a component in the elementui, which can only be used by introducing elementui. However, this method obviously needs more convenient callbacks, which can easily handle various common upload problems.
  3. The second method can meet the conventional upload requirements, but if you want to customize the upload method, it is still recommended to use the first upload scheme.

2. Pass the token manually

For the above different file upload methods, there are different schemes for manually uploading tokens. SongGe will introduce them one by one. Here, the server authentication is oauth2 + JWT, so the next token passing is mainly in the form of oauth2. In fact, the request header is modified. As long as this method is used, other methods will also be used.

About oauth2, if you are not familiar with it, you can take a look at the series of tutorials written by SongGe before: oauth2 series

2.1 Ajax delivery token

Ajax passing tokens is actually very easy, we just need to modify the request header slightly. Let me give you a simple example.

If you use Axios to make network requests, you can add request headers as follows (or add them uniformly in the request interceptor) as follows:

export const uploadFileRequest = (url, params) => {
  return axios({
    method: 'post',
    url: `${base}${url}`,
    data: params,
    headers: {
      'Content-Type': 'multipart/form-data',
      'Authorization': 'Bearer ' + token
    }
  });
}

If you use jQuery, you can add a request header as follows:

$("#btnClick").click(function () {
        var formData = new FormData();
        formData.append("file", $("#userface")[0].files[0]);
        $.ajax({
            url: '/fileupload',
            type: 'post',
            headers: {
                'Authorization': 'Bearer ' + token
            },
            data: formData,
            processData: false,
            contentType: false,
            success: function (msg) {
                alert(msg);
            }
        });
    });

It is nothing more than modifying the request header. As long as the request is sent by yourself, the request header can be customized freely, whether you use jQuery, Axios or native XMLHttpRequest.

2.2 El upload processing token

If we use El upload, we will have to play in other people’s frameworks to meet the requirements of the framework. Although there are more constraints, it is not impossible to achieve. Here, SongGe will introduce two solutions.

2.2.1 scheme I

The first scheme is the one I currently use, because El upload supports customized request headers, which is easy to do

<el-upload
  ref="upload"
  class="upload-container"
  :data="category"
  :multiple="false"
  :limit="1"
  :headers="myHeaders"
  :auto-upload="false"
  :on-success="onSuccess"
  :on-error="onError"
  :file-list="fileList"
  action="/appmanager/app/categories/"
>
  < El button size = "mini" type = "primary" > select icon < / El button >
</el-upload>

Where: headers = “myheaders” is my customized request header, and then define the variable in the data

data() {
  return {
    myHeaders: { Authorization: 'Bearer ' + getToken() }
  }
},

2.2.2 scheme 2

The second scheme is to use the before upload hook function of El upload. Developers can upload manually in this hook function. After the upload is completed, a false will be returned, and then El upload will stop its own upload logic. I can see that there are other partners using this method, so let’s give you a simple case for reference

<el-upload action="http://www.javaboy.org" :before-upload="beforeUpload"></el-upload>
beforeUpload (file) {
    //Refer to the above Ajax or Axios upload file
    return false
}

Here are some details that you need to pay attention to:

  1. The action attribute of El upload can be given a value at will to avoid error, because the real upload address will be given in the beforeupload method.
  2. The upload logic of the beforeupload method is consistent with what we described in the first section. I will not repeat it. Note that the uploaded file object isfile.raw
  3. The beforeupload method eventually returns false to terminate El upload’s own upload logic.

3. Summary

OK, I introduced several token passing methods when uploading files with my friends. Do you know if you have got it? If you have any questions, please leave a message for discussion. If you have learned, please click on the song Ge to encourage you