phonegap檔案上傳(Java,PHP)
phpnegap檔案上傳
phonegap中的FileTransfer對象介紹:
http://docs.phonegap.com/en/1.6.1/cordova_file_file.md.html#FileTransfer
?
今天的代碼為同學所整理。在此記下來,供以後參考
?
FileTransfer?is an object that allows you to upload files to a server or download files from a server.
?
用於傳檔案到伺服器端
?
它裡面有樣本,寫得已經是非常的詳細,其中有一段:
var options = new FileUploadOptions();options.fileKey="file";options.fileName=fileURI.substr(fileURI.lastIndexOf('/')+1);options.mimeType="text/plain";
?
前端的完整版可以參考:http://www.oschina.net/question/200138_34919
?
今天在做圖片上傳的時候,怎整也無法在後端擷取檔案流,其中的Java邏輯如下:
int MAX_SIZE = 102400 * 102400;DataInputStream in = null;FileOutputStream fileOut = null;String contentType = request.getContentType();try {if (contentType.indexOf("multipart/form-data") >= 0) {in = new DataInputStream(request.getInputStream());int formDataLength = request.getContentLength();if (formDataLength > MAX_SIZE) {return;}byte dataBytes[] = new byte[formDataLength];int byteRead = 0;int totalBytesRead = 0;while (totalBytesRead < formDataLength) {byteRead = in.read(dataBytes, totalBytesRead, formDataLength);totalBytesRead += byteRead;}String file = new String(dataBytes);String saveFile = file.substring(file.indexOf("filename=\"") + 10);saveFile = saveFile.substring(0, saveFile.indexOf("\n"));saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1, saveFile.indexOf("\""));int lastIndex = contentType.lastIndexOf("=");String boundary = contentType.substring(lastIndex + 1,contentType.length());int pos;pos = file.indexOf("filename=\"");pos = file.indexOf("\n", pos) + 1;pos = file.indexOf("\n", pos) + 1;pos = file.indexOf("\n", pos) + 1;int boundaryLocation = file.indexOf(boundary, pos) - 4;// 取得檔案資料的開始的位置int startPos = ((file.substring(0, pos)).getBytes()).length;// 取得檔案資料的結束的位置int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;// 建立檔案的寫出類fileOut = new FileOutputStream(System.getProperty("java.io.tmpdir") + "/aa.jpg");// 儲存檔案的資料fileOut.write(dataBytes, startPos, (endPos - startPos));fileOut.close();} } catch (Exception ex) {throw new ServletException(ex.getMessage());}
?後來才發現,原來是少了一個致命的參數:options.chunkedMode = false;
?
關於chunkedMode的解析,請看:http://www.issociate.de/board/post/368589/How_to_force_the_apache_transfer_the_data_in_chunked_mode?.html
?
大意是:如果檔案長度無法預知時,使用chuckedMode模式傳輸,現在傳輸的是圖片,大小已經知道,不知道為何apache伺服器處理不過來,一定要將chunkedMode設成false,至此上傳成功,感覺同學指點
?
為了這個參數,我還對比了php版本的檔案上傳:php的server端這樣寫的:
// If retrieving an imageelse if (isset($_GET['image'])) { $file = $dirname."/".$_GET['image']; // Specify as jpeg header('Content-type: image/jpeg'); // Resize image for mobile list($width, $height) = getimagesize($file); $newWidth = 120.0; $size = $newWidth / $width; $newHeight = $height * $size; $resizedImage = imagecreatetruecolor($newWidth, $newHeight); $image = imagecreatefromjpeg($file); imagecopyresampled($resizedImage, $image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height); imagejpeg($resizedImage, null, 80); }// If displaying imageselse { $baseURI = "http://".$_SERVER['SERVER_NAME'].':'.$_SERVER['SERVER_PORT'].$_SERVER['REQUEST_URI']; $images = scandir($dirname); $ignore = Array(".", ".."); if ($images) { foreach($images as $curimg){ if (!in_array($curimg, $ignore)) { echo "Image: ".$curimg."
"; echo "
"; } } } else { echo "No images on server"; }}?>
?php的代碼參考:https://github.com/brycecurtis/articles/tree/master/CameraUpload
?
代碼說明及解說在:https://www.ibm.com/developerworks/mydeveloperworks/blogs/94e7fded-7162-445e-8ceb-97a2140866a9/entry/upload_a_picture_using_phonegap_on_android8?lang=en
?
php版本的這個前端代碼:
// Verify server has been entered server = document.getElementById('serverUrl').value; if (server) { // Specify transfer options var options = new FileUploadOptions(); options.fileKey="file"; options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1); options.mimeType="image/jpeg"; options.chunkedMode = false; // Transfer picture to server var ft = new FileTransfer(); ft.upload(imageURI, server, function(r) { document.getElementById('camera_status').innerHTML = "Upload successful: "+r.bytesSent+" bytes uploaded."; }, function(error) { document.getElementById('camera_status').innerHTML = "Upload failed: Code = "+error.code; }, options); }
?確實是含有chunkedMode=false的設定,並在本機運行通過。