2016-10-25 26 views
1

我正在使用TypeScript和Haml。我希望能夠使用vue.js上傳和查看文件。我可以上傳圖片,但它應該顯示它馬上爲演示了此:https://codepen.io/Atinux/pen/qOvawK/使用VueJS上傳和查看輸入文件

相反,我得到這個錯誤:

http://localhost:8080/image無法加載資源:服務器與404狀態迴應(未找到)

如果它試圖從根目錄獲取圖像,我的問題是我沒有保存它嗎?我將如何解決這個問題?

page_image.ts:

require("./page_image.scss"); 
import Vue = require("vue"); 
import {Injections} from "../../init"; 

export const PageImage = { 
template: require("./page_image.haml"), 
data: function() { 
    return { 
     image: '' 
    } 
}, 

created() { 
    Injections.HeaderTextManager.setHeader("Videos"); 
    Injections.HeaderTextManager.clearDescription(); 
}, 

methods: { 
    onFileChange(e:any) { 
     var files = e.target.files || e.dataTransfer.files; 
     if (!files.length) 
      return; 
     this.createImage(files[0]); 
    }, 
    createImage(file:any) { 
     var image = new Image(); 
     var reader = new FileReader(); 
     var vm = this; 

     reader.onload = (e:any) => { 
      vm.image = e.target.result; 
     }; 
     reader.readAsDataURL(file); 
    }, 
    removeImage: function (e:any) { 
     this.image = ''; 
    } 
} 
}; 

page_image.haml:

.page-image 
    .row 
    .col-xs-12 
    .box 
     .box-header 
     %div(v-if="!image") 
      %h3.box-title Upload an image 
      %input(type="file" v-on:change="onFileChange") 
     %div(v-else) 
      %img(src="image" name="image") 
      %img {{image}} 
      %button(v-on:click="removeImage") Remove image 
+0

您的代碼只能讀取瀏覽器中的圖像。您必須先使用某種XHR將其發送到服務器,然後才能夠轉向並從服務器加載它。 –

+1

你知道你可以使用'URL.createObjectURL(文件)'而不是使用文件讀取器... – Endless

回答

0

我不知道haml,我不vue.js使用打字稿。所以我不能給你一個直接的答案。

這裏是實現FileReadervue.js提供即時預覽工作的jsfiddle例如: https://jsfiddle.net/mani04/5zyozvx8/

你可以使用上面提到調試代碼。

這是它是如何工作的:爲了使FileReader正常工作,我們需要訪問input的DOM元素。這可以如下完成:

<input type="file" @change="previewImage" accept="image/*"> 

previewImage方法獲取event參數,其中有event.target - 爲input,我們需要的DOM元素。現在,您的previewImage方法可以正常讀取的圖像文件,如下所示:

previewImage: function(event) { 
    // Reference to the DOM input element 
    var input = event.target; 
    // Ensure that you have a file before attempting to read it 
    if (input.files && input.files[0]) { 
     // create a new FileReader to read this image and convert to base64 format 
     var reader = new FileReader(); 
     // and so on... 

你可以使用這個的jsfiddle作參考,並保持這個問題開放,讓別人用的hamltypescript知識可以提供更直接的答案。

+0

請忽略我上面的答案......它與你給出的codePen例子是一樣的,我現在才注意到它。 – Mani

0

我認爲這個問題是因爲這條線在你的page_image.haml

%img(src="image" name="image") 

造成的。如果將其轉換或編譯爲<image src="image" name="image">,那麼你的瀏覽器將尋找圖像中localhost:8080/image,而不是嘗試從data.image顯示在Vue組件內部。

正如我在其他答案中所解釋的,我不知道haml,所以你必須找出一種方法來解決它自己。

編輯:

看在你的問題其他haml代碼,工作的呢?

%img(v-bind:src="image" name="image")