【问题标题】:Upload file to public folder of vuejs将文件上传到 vuejs 的公共文件夹
【发布时间】:2020-03-26 07:48:39
【问题描述】:

想知道是否有办法使用 vuejs 编码在公共文件夹中上传文件 我确实有一个代码,但它是为了在 laravel 公共文件夹中移动文件而构建的。 vuejs有这种功能吗?

这是我目前的功能。希望大家帮帮我

表单代码

<!-- Form Upload -->
            <div class="row">
              <div class="col-sm-6 offset-3">
                <div class="form-group">
                  <label for="exampleFormControlFile1">Upload</label>
                  <input
                    type="file"
                    ref="file"
                    class="form-control-file"
                    @change="onFileChange"
                  >
                  <small class="text-muted">
                    for slideshow images
                    <br />
                     size: 1280 x 630 pixel for good quality
                  </small>
                </div>
              </div>
            </div>
          </div>
          <div class="modal-footer">
            <button
              type="button"
              class="btn btn-primary"
              data-dismiss="modal"
              @click="uploadFile"
              :disabled="disableBtn"
            >Upload</button>
          </div>

方法代码

onFileChange(e) {
  this.file = this.$refs.file.files[0];
},
uploadFile() {
  if (this.file == "") {
    this.alertClass = "alert alert-danger";
    this.alertMessage = "Please select a file";
    this.showAlert = true;
  } else {
    this.disableBtn = true;
    this.$parent.showLoading();
    let requestUrl =
      this.baseUrl  + "/media";
    let formData = new FormData();
    formData.append("file", this.file,);
    formData.append("mediatype", this.Mediatype);
    let headers = {
      headers: {
        "Content-Type": "multipart/form-data"
      }
    };

    this.$http
      .post(requestUrl, formData, headers)
      .then(response => {
        this.alertClass = "alert alert-success";
        this.alertMessage = response.data.message;
        this.$refs.file.value = ''
        this.showAlert = true;
        this.$parent.hideLoading();
        this.disableBtn = false;
        this.$parent.getGallery();
      })
      .catch(() => {
        this.disableBtn = false;
        this.$parent.hideLoading();
        this.alertClass = "alert alert-danger";
        this.alertMessage =
          "There is a problem in the request.";
        this.showAlert = true;
      });
  }
}

【问题讨论】:

    标签: function vue.js import


    【解决方案1】:
    //Follow this instruction
    File
    <input
    type="file"
    ref="image2"
    v-on:change="handleFilesUpload()"
    />
    In methods properties 
    handleFilesUpload() {
          let uploadedFiles = this.$refs.image2.files;
          let fileExtension = uploadedFiles[0].name.replace(/^.*\./, "");
          //console.log("fileExtension", fileExtension);
    
          let allowedExtensions = /(\.jpg|\.JPG|\.jpeg|\.JPEG|\.png|\.PNG|\.pdf|\.PDF|\.doc|\.docx)$/i;
          if (!allowedExtensions.exec(uploadedFiles[0].name)) {
           var message = "You can upload jpg, jpeg, png, pdf and docx file only";     
            this.$refs.image2.value = "";
            this.documentFiles = [];
          } else {
            //console.log("uploadedFiles[i] = ", uploadedFiles[0]);     
            //Upload for single file        
            this.documentFiles = uploadedFiles;
            //Upload for multiple file
            /*
            for (var i = 0; i < uploadedFiles.length; i++) {
              this.documentFiles.push(uploadedFiles[i]);
            }
            */
          }
        },
    // After submit form
    validateBeforeSubmit(e) {
          let formData = new FormData();  
          for (var i = 0; i < this.documentFiles.length; i++) {
            let file = this.documentFiles[i];
            formData.append("files[" + i + "]", file);
          } 
          axios.post('laravel-api-url', formData)
          .then(res => {
                  console.log({res});
              }).catch(err => {
              console.error({err});
            });
        },
    --In Laravel controller function--
    public function save($request){
            $total = @count($_FILES['files']['name']);
                if ($total>0)
                {
                    $allFiles = $this->uploadFiles($request);
                    $data['document_file_name'] = ($allFiles) ? $allFiles[0] : 
                    $result = CreditMaster::create($data);
                    if ($result) {
                        return response()->json(array('status' => 1,
                        'message' => 'Data saved successfully!'));
                    } else {
                        return response()->json(array('status' => 0, 'message' => 'Save failed!'));
                    }
                }
    }
    public function uploadFiles($request)
        {
            $storeFileName = [];
            $total = @count($_FILES['files']['name']);
            $diretory = '/save_directory_name/';
            $path = public_path() . $diretory;
            $fileForMate = time() . '_';
            for ($i = 0; $i < $total; $i++) {
                $tmpFilePath = $_FILES['files']['tmp_name'][$i];
                if ($tmpFilePath != "") {
                    $fileName = $fileForMate . $_FILES['files']['name'][$i];
                    $newFilePath = $path . $fileName;
                    if (move_uploaded_file($tmpFilePath, $newFilePath)) {
                        array_push($storeFileName, $diretory.$fileName);
                    }
                    else
                    {
                        return $_FILES["files"]["error"];
                    }
                }
            }
            return $storeFileName;
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-01-27
      • 2018-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多