2013-12-15 3 views
2

나는이 질문에 대한 정직한 대답을 위해 높고 낮게 보았다.Ajax를 통해 서버에 저장된 이미지를 로컬로 전송

/image/test.png 

내가 양식 데이터를 사용하여 여러 부분 양식의 일부로 서버에이 이미지를 보낼 :

나는 다음 디렉토리에서 전화 갭 응용 프로그램에서 로컬로드 이미지를 가지고있다.

var formdata = new FormData(); 

그때

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

내가 다음 이미지를 추가 할 내 JSON 추가 물론 나를 위해 작동하지 않는 경우 나는 다음과 같은

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 플러그인을 사용할 수 있습니다. 포스트 폰갭 3에서 당신은

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

서버에 업로드하기 위해이 같은 일을 할 당신의 Config.xml의 플러그인을 포함 할 필요가 : 참고

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.) 당시의 문제점이 있습니다.

자세한 내용은 여기에서 설명서를 참조하십시오. 당신은 당신의 안드로이드 매니페스트에서 파일 및 파일 전송 플러그인을 활성화해야합니다

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); 

: http://docs.phonegap.com/en/3.2.0/cordova_file_file.md.html#FileTransfer

여기에 빠른 예입니다.

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

알려진 문제에 대한 빠른 메모 ... 업로드는 다른 모든 후속 업로드에 실패합니다 (예 : 성공, 실패, 성공, 실패, 등 ....) -이 문제가 영향을 미쳤다합니다 iOS 및 Android (BB 또는 다른 플랫폼에 대해서는 말할 수 없습니다.) AFAIK, Android는 여전히 영향을 받지만, 나는 read the thread을 권유하고 있습니다. 솔루션/해결 방법은, 그러나 그들은 또한 실패보고가 추천

(예. 청크 분할 모드를 해제하고 가까운 연결을 강제로 시도.)

신뢰할 수있는 수정이있을 때까지, 그것은 단순히를하는 것이 좋습니다 시도 된 연결 카운터를 유지하고 짝수 번호가 지정된 실패를 원인으로 처리하여 즉시 다시 시도하십시오. (불쾌하지만 필요합니다.)

+0

추가 게시물 데이터로 이미지를 업로드하는 안드로이드에 문제가 없습니다. 내 답변에 명시된 업로드 옵션을 사용하고 있습니다. 업로드 오류가 전혀 없습니다 ... –

+0

내가 말했듯이, 위에 링크 된 스레드를 참조하십시오. 확실히 모든 장치에 영향을주는 것으로 보이지는 않지만 읽는 것처럼 널리보고됩니다. – ocodo

+0

@kasperTaeymans 경우에 따라 닫기/청크로 문제를 해결하지만 다른 경우에는 그렇지 않습니다. - fyi, 필자는 "Connection : close"를 추가 할 것이다. – ocodo

0

이미지 (= 파일)를 업로드하려하지만 실제로는 img.src에 의해 반환 된 문자열을 게시하고 있습니다. 이미지를 게시하려면 게시 할 수있는 문자열로 변환해야합니다. 캔버스 요소에 이미지를로드하고 toDataUrl으로 전화하여이 작업을 수행 할 수 있습니다. 그러나 phonegap을 사용할 때 filetransfer를 통해 파일을 업로드하고 추가 게시물 데이터를 추가하는 것이 좋습니다 ...

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

그런 다음 해당 지역의 이미지 base64 인코딩을 얻을 아약스를 사용하여 서버로 전송이 plugin을 사용할 수 있습니다 :

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

그런 다음 javascript async 또는 promises를 사용하여 모든 파일에 대해 base64를 모두 가져와야합니다 서버 전체 배열을 보내십시오 –

+0

Hello Hazem. 내가 보는 문제는 함수 (base64)를 호출 할 때 인코딩 된 파일을 알 수 없다는 것입니다 (filePath를 사용할 수 없습니다) 생각하므로 예를 들어 바라기를, 나는 틀렸다. –

관련 문제