2016-01-29 60 views
0

我使用HTML5輸入使用以下線採取從相機拍攝照片的文件夾上拍攝的圖像,保存其通過本地計算機上的照相機

<input id="cameraInput" type="file" accept="image/*;capture=camera"></input> 

和斑點獲得用於圖像:,使用以下JavaScript中,

var mobileCameraImage = function() { 
    var that = this 
     ; 
     $("#cameraInput").on("change", that.sendMobileImage); 
     if (!("url" in window) && ("webkitURL" in window)) { 
     window.URL = window.webkitURL; 
     } 
}); 

var sendMobileImage = function(event) { 
    var that = this; 
     if (event.target.files.length == 1 && event.target.files[0].type.indexOf("image/") == 0) { 
      var capturedImage = URL.createObjectURL(event.target.files[0]) 
       ; 

      alert(capturedImage); 
     } 
}); 

在這裏,我得到正確的圖像URL,但我面臨的問題是到該圖像的URL發送到服務器,閱讀博客後我發現我不能送斑點:URL服務器因它的本地實例。有沒有人可以幫助保存點擊圖像本地計算機上的文件夾或任何地方,或幫助我如何發送這個圖像網址到服務器。

在此先感謝。

+0

難道你真的不想把*圖像*發送到服務器,而不是一個objectURL? – adeneo

+0

我試圖保存圖像,然後想要發送圖像URL後,因此服務器可以執行一些任務。 – Soarabh

+0

但是你不能發送一個objectURL到服務器並訪問那個圖像服務器端,那個URL只存在於瀏覽器中,你必須發送**整個圖像**到服務器去執行任何事情,然後發送它再次回到客戶端。 – adeneo

回答

0

您可能需要每次通過Ajax提交表單,或者您可以手動上傳圖像數據。爲了做到這一點,您可以將圖像繪製到畫布上,然後獲取畫布數據。

// create an image to receive the data 
var img = $('<img>'); 

// create a canvas to receive the image URL 
var canvas = $('<canvas>'); 
var ctx = canvas[0].getContext("2d"); 

$("#cameraInput").on("change", function() { 
    var capturedImage = URL.createObjectURL(this.files[0]); 

    img.attr('src', capturedImage); 
    ctx.drawImage(img); 

    var imageData = canvas[0].toDataURL("image/png"); 

    // do something with the image data  
}); 

或者使用FileReader

// only need to create this once 
var reader = new FileReader(); 
reader.onload = function() { 
    var imageData = reader.result; 

    // do something with the image data 
}; 

$("#cameraInput").on("change", function() { 
    reader.readAsDataURL(this.files[0]); 
}); 

然後你就可以將數據上傳到服務器。

+0

爲什麼OP需要這樣做,他已經有了圖像,並沒有提到需要Base 64字符串的任何內容? – adeneo

+0

我分享這個,因爲我不得不爲我們的用戶頭像軟件編寫類似的代碼,我需要在將圖像發送到服務器之前裁剪圖像。爲此,我使用了[Jcrop](http://jcrop.org/),這允許我發送其他數據(即用戶信息)並在本地訪問圖像數據進行操作。我認爲這是OP要求的。 –

相關問題