preface

The coreui/ VUE based back office management project I was in charge of recently ran into difficulties. When developing the product listing function, the uploaded picture data was always empty when the form was submitted, and the parameters could not be carried. But it is possible to print the file data normally before sending the request.

Try to solve

  1. Set the content-type
let config = {
    headers: {
      "Content-Type": "multipart/form-data"}}; this.$http
    .post("/product/add", params, config)
    .then().catch()
Copy the code

The result is not OK.

  1. Try the component’s other API for files field assignment. Is the V-Model invalid?
<b-form-group label="Product thumbnail" label-for="fileInput" :label-cols="3"> <! -- plain: use the default raw style, multiple: select --> <b-form-file id="fileInput"
  v-model="goodsData.files"
  placeholder="Choose a picture"
  drop-placeholder="Drag the image here."
  accept="image/*"
  browseText="Browse"
  @change="uploadPicture"
  @input="selectPicture"></b-form-file> </b-form-group> // methods uploadPicture(e) {console.log(e.targe.files); }, selectPicture(val) { console.log(val); }Copy the code

The result is still not good.

  1. Attempts to manipulate the name attribute of b-form-file still fail.

transit

In recent days, the management system project schedule to the test environment, the corresponding small program to experience version. On the Internet again to check the file upload, running a file upload case online, found the need for new FormData instance, files file data append into the instance can be.

To solve

Example code:

 onSubmit() {
  if (Object.values(this.goodsData).indexOf("") !== -1) {
    this.showErrorMsg({ message: "Blank if required" });
    return;
  }
  if (this.goodsData.files.length === 0) {
    this.showErrorMsg({ message: "Please upload at least one picture." });
    return; } // Form submission, data processinglet params = new FormData();
  // params.append('files', this.goodsData.files)
  for (let key in this.goodsData) {
    params.append(key, this.goodsData[key]);
  }
  let config = {
    headers: {
      "Content-Type": "multipart/form-data"}}; this.$http
    .post("/product/add", params, config)
    // .post("/product/add", enclosing goodsData). Then (res = > {/ / slightly}). The catch (error = > {/ / slightly}); },Copy the code

The problem was solved perfectly.

conclusion

Vue + AXIos file upload after getting the file data also need to meet the following conditions

  1. The default content-type is JSON and must be set to formData format.
  2. New FormData instance, passing the argument append into the instance.

Refer to the article

Vue +axios Uploads files