【问题标题】:How to get old image in edit form with VueJS?如何使用 VueJS 以编辑形式获取旧图像?
【发布时间】:2020-04-24 01:39:54
【问题描述】:

我无法在编辑表单中显示旧图像。我已将上传的图像存储在 laravel 项目公共文件夹内的 img 文件夹中。以下是我用于保存和编辑表单数据的代码。如何以编辑形式显示旧上传的图像? 请帮帮我。

   <input type="file" id="file-upload" @change="onFileChange" src="{{ asset('newapplicant.photo') }}">

脚本

save() {

const saveUrl = `/api/registration/${this.registrationId}/applicant`;
               VueAxios.post(saveUrl, this.formData, {
                       headers: {
                           'X-Requested-With': 'XMLHttpRequest',
                           Authorization: `Bearer ${window.localStorage.getItem('token')}`,
                       },
                   }, {
                       timeout: 10000,
               })
               .then((response) => {            
               if (response.status === 200 || response.status === 201) {
               this.applicant.push(response.data.data);
               this.successfulMessage = 'Successful.';
               this.clearAllData();
               }
               })
               .catch((error) => {                 
                   console.log(`api error:${error}`);
               });
            },
           edit(id) {
             const url = `api/registration/${this.$route.params.regId}/applicant/${id}`;
              VueAxios.get(url, {
                   headers: {
                       'X-Requested-With': 'XMLHttpRequest',
                       Authorization: `Bearer ${localStorage.getItem('token')}`,
                   },
               }, {
                   timeout: 100000,
               })
               .then((response) => {
                   // debugger;
                   this.newapplicant = response.data.data;
               });
           },

【问题讨论】:

    标签: vue.js


    【解决方案1】:

    其中一种方式可能是这样的:

    第 1 步:在您的 .vue 文件中,在您的 created 方法中,获取您当前的图片网址

    第 2 步:将该值保存在 data 对象的单独属性中 - 例如,originalFile

    第 3 步:不要将文件上传控件直接绑定到新值。为此使用另一个 data 属性 - 例如,currentFile

    第 4 步:从您的 onchange 处理程序更新您的 currentFile 属性,当用户上传新图像时,将这个新的 imageFile 名称/src 分配给您的 originalFile 属性。

    因此,您的代码可能看起来像这样: (这是我最近参与的一个项目的摘录)

    ...
    ...
    ...
    components: { DatePicker },
      data() {
        return {
          isLoading: false,
          imgFile: null,
          curImgUrl: "",
          filesSelected: 0
        };
      },
      created() {
        this.fetchUserPhotos();
      },
      methods: {
        handleFileChange: function(event) {
          if (!this.imgFile) {
            return;
          }
          // validate file size
          if (this.imgFile.size > 10000000) {
            U.showError("File larger than 10MB cannot be uploaded.");
            setTimeout(this.discardImage, 200);
            return;
          }
          let reader = new FileReader();
          reader.addEventListener(
            "load",
            function(e) {
              this.curImgUrl = e.target.result;
            }.bind(this)
          );
          reader.readAsDataURL(this.imgFile);
        },
        discardImage() {
          this.imgFile = null;
          this.curImgUrl = "";
        },
        fetchUserPhotos() {
          this.isLoading = true;
          PhotoService.getUserPhotos()
            .then(response => {
              this.userPhotos = response;
              this.isLoading = false;
            })
            .catch(error => {
              console.log(error);
              this.isLoading = false;
              U.showError(error);
            });
        },
        savePhoto() {
          if (this.caption == undefined || this.caption.trim().length < 4) {
            U.showError("Please add a caption.");
            return;
          }
    
          U.showBusy();
    ...
    ...
    ...
    

    在你的 vue 模板中你可以做这样的事情:

    <v-row justify="center">
                      <v-col cols="12">
                        <v-file-input
                          chips
                          label="Add Photo"
                          color="secondary"
                          accept="image/*"
                          persistent-hint
                          hint="max size: 2MB"
                          truncate-length="18"
                          v-model="imgFile"
                          show-size
                          @change="handleFileChange"
                          @click:clear="discardImage"
                          :disabled="isLoading"
                        ></v-file-input>
                      </v-col>
                      <v-col cols="12">
                        <v-layout justify-center>
                          <v-btn
                            small
                            class="mx-2"
                            color="error"
                            dark
                            :disabled="(isLoading || imgFile == null && imgFile == undefined)"
                            @click="discardImage"
                          >Discard</v-btn>
                        </v-layout>
                      </v-col>
                      <v-col cols="12" v-if="curImgUrl">
                        <v-img :src="curImgUrl" aspect-ratio="1.7" contain></v-img>
                      </v-col>
                    </v-row>
    

    PS:我是用手机发的,所以格式可能有点乱

    【讨论】:

    • 为了预览,你应该使用一个单独的图片标签,它的 src 设置为 curImgUrl,或者在你的情况下,asset('newapplicant.photo').
    猜你喜欢
    • 2018-10-02
    • 2020-05-05
    • 2021-05-10
    • 2022-01-05
    • 2013-09-05
    • 1970-01-01
    • 1970-01-01
    • 2021-10-15
    • 1970-01-01
    相关资源
    最近更新 更多