2013-12-15 187 views
2

我看了這個問題的直接答案的高低。通過Ajax發送本地存儲的圖像到服務器

我在下面的目錄電話間隙應用本地加載圖像:

/image/test.png 

我想這個圖像發送到服務器使用表單數據的多部分形式的一部分。

var formdata = new FormData(); 

我再追加我的JSON

formdata.append("json", JSON.stringify(request)); 

我則希望將圖像追加和我嘗試使用以下

var img = new Image(); 
img.src = './image/test.png'; 

formdata.append("file", img.src); 

$.ajax(
{ 
    url : "http://myserver:8080/myservlet", 
    type : "POST", 
    data : formdata, 
    processData : false, 
    contentType : false, 
    dataType : "json", 
    success : function(response) 
    { 
    console.log("success response:"+JSON.stringify(response)); 
    }, 
    error : function(jqXHR,textStatus,errorThrown) 
    { 
    var msg = "Error Sending File. Status: "+textStatus+" Error:"+errorThrown; 
    navigator.notification.alert(msg, null, "Error", "OK"); 
    } 
}); 

這如果課程不適合我的工作 - 我是什麼我做錯了。

回答

0

在phonegap上,您可以使用FileTransfer插件。在後PhoneGap的3你必須包括在你的config.xml中的插件

<gap:plugin name="org.apache.cordova.file" /> 
<gap:plugin name="org.apache.cordova.file-transfer" /> 

然後上傳到服務器上做這樣的事情:

var imageUploadSuccess = function (data) { 
     alert("Cool"); 
    } 
    var imageUploadFail = function (error) { 
    alert("fail"); 
    } 

    var params = new Object(); 
    params.yourHttpParam = "My Param Value"; 
    var url ="http://myserver.com/photo/upload"; 

    var options = new FileUploadOptions(); 
    options.fileName = "/image/test.png"; 
    options.mimeType = "image/png"; 
    options.fileKey = "file"; 
    options.params = params; 
    options.chunkedMode = false; 
    var ft = new FileTransfer(); 
    ft.upload("/image/test.png", url, imageUploadSuccess, imageUploadFail, options, true); 
+0

注意,如果你從相機/ imageURI,使用上傳:'imageURI .substr(imageURI.lastIndexOf('/')+ 1)'獲取文件名。 – ocodo

+0

感謝讓我檢查發送其他項目作爲參數,我假設這使用POST和表單數據類型在幕後傳輸。 – simapp

+0

這是一篇文章,該文件將是一個Miltipart文件,但是你在服務器上實現 – DavidC

0

您需要使用FileTransfer API,注意在撰寫本文時有一些問題(however they are being addressed.)。

有關詳細信息,請參閱此處的文檔。 http://docs.phonegap.com/en/3.2.0/cordova_file_file.md.html#FileTransfer

這裏有一個簡單的例子:

var fileURI = // imageURI returned by the CameraAPI. 

var success = function (r) { 
    console.log("Code = " + r.responseCode); 
    console.log("Response = " + r.response); 
    console.log("Sent = " + r.bytesSent); 
} 

var fail = function (error) { 
    alert("An error has occurred: Code = " + error.code); 
    console.log("upload error source " + error.source); 
    console.log("upload error target " + error.target); 
} 

var options = new FileUploadOptions(); 
options.fileKey = "file"; 
options.fileName = fileURI.substr(fileURI.lastIndexOf('/') + 1); 
options.mimeType = "text/plain"; 

// The following options are to attempt circumvention of the 
// FileTransfer.upload issues in the linked Cordova thread. 
// Note that they are reportedly, not always effective. 
options.headers={Connection: "close"}; 
options.chunkedMode = false; 

var params = {}; 
params.value1 = "test"; 
params.value2 = "param"; 

options.params = params; 

var ft = new FileTransfer(); 
ft.upload(fileURI, encodeURI("http://some.server.com/upload.php"), success, fail, options); 

您將需要啓用您的Android清單文件和文件傳輸的插件。

<gap:plugin name="org.apache.cordova.file" /> 
<gap:plugin name="org.apache.cordova.file-transfer" /> 

有關已知問題的快的筆記...上傳會失敗每隔隨後上傳(即成功,失敗,成功,失敗,等等。) - 請注意,這個問題已經影響iOS和Android(我不能說BB或其他平臺。)AFAIK,Android仍然受到影響,但我建議你read the thread並密切關注它。

有推薦的解決方案/變通方法,但它們同時報告失敗(即關閉分塊模式,並試圖強行關閉連接。)

直到有一個可靠的修復,最好是簡單地保留一個嘗試的連接計數器,並將偶數編號的失敗作爲原因立即重新嘗試。 (討厭的,但必要的)。

+0

我沒有問題在Android上載圖像與額外的發佈數據。我正在使用我的答案中所述的上傳選項。我沒有任何上傳錯誤... –

+0

正如我所說,請參閱上面鏈接的線程。它看起來似乎不會影響每一個設備,但正如你會讀到的,它被廣泛報道。 – ocodo

+0

@kasperTaeymans在某些情況下,關閉/分塊修復了這個問題,但是在其他情況下,沒有。 - fyi,我會在我的示例中添加「Connection:close」。 – ocodo

0

您正在嘗試上傳圖片(=文件),但實際上您發佈的是由img.src返回的字符串。如果您想發佈圖片,則需要將其轉換爲可發佈的字符串。你可以通過加載你的圖像到一個畫布元素,並獲得撥打電話toDataUrl。但是,當使用phonegap時,我建議通過文件傳輸上傳文件並添加額外的發佈數據給它...

function uploadPhoto(imageUrlToUpload) { 
    //alert('upload: '+imageUriToUpload); 
    var url=encodeURI(youruploadurl); 
    var params = new Object(); 
    params.your_param_name = "something"; //add your additional post parameters here 
    var options = new FileUploadOptions(); 
    options.headers={Connection: "close"}; 
    options.fileKey = "file"; //depends on the api 
    options.fileName = imageUriToUpload.substr(imageUriToUpload.lastIndexOf('/')+1); 
    options.mimeType = "image/jpeg"; 
    options.chunkedMode = false; //this is important to send both data and files 
    options.params = params; 

    var ft = new FileTransfer(); 
    //what to do during the file transfer? lets show some percentage... 
    var status=$('yourselectorhere');//element in the dom that gets updated during the onprogress 
    ft.onprogress = function(progressEvent) { 
     var perc; 

     if (progressEvent.lengthComputable) { 


       perc = Math.ceil(progressEvent.loaded/progressEvent.total * 100); 

       status.html(perc+'%'+ '('+progressEvent.total+')'); 

     }else{alert('not computable');} 
    }; 

    ft.upload(imageUrlToUpload, url, success, fail, options); 
} 

function success(r) { 
    alert("Upload success: Code = " + r.responseCode); 
} 

function fail(error) { 
    alert("An error has occurred: Code = " + error.code); 
} 
+0

在傳遞額外的參數 - 我試圖找到一個平行形式的數據,所以我假設我有一個名稱和一個值參數。那麼formdata.append(「name」,「value」等於params.name =「value」?而且這基本上是一個多/部分POST? – simapp

3

你可以使用這個plugin讓你的局部圖像的base64編碼,然後使用AJAX發送到服務器:

window.plugins.Base64.encodeFile(filePath, function(base64){ 
     console.log('file base64 encoding: ' + base64); 
     //write down ajax code to send base64 string 
    }); 
+1

然後你必須獲得所有使用JavaScript異步或承諾的所有文件的base64,然後發送整個數組到服務器 –

+0

Hello Hazem。我看到的問題是,當調用函數(base64)時,我無法知道哪個文件已被編碼(我認爲filePath不可用),因此我無法將其設置爲希望我錯了。 –