PhoneGap 上傳圖片HTML和服務器端端實現(JAVA)

HTML代碼  利用PhoneGap本身實現的API  FileTransfer 的 upload 代碼 javascript

<!DOCTYPE HTML>

<html>
<head>
<title>PhoneGap_dataTransfer</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="stylesheet" href="css/jquery.mobile-1.2.0.min.css">
<script type="text/javascript" charset="utf-8" src="js/jquery.js"></script>
<script type="text/javascript" charset="utf-8"
	src="js/jquery.mobile-1.2.0.min.js"></script>
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript">
	$(document).bind("mobileinit", function() {

		//$.mobile.autoInitialize = false; //刪除這行配置參數就會出現渲染錯誤

		$.support.cors = true;

		$.mobile.allowCrossDomainPages = true;

	});

	var pictureSource; // picture source

	var destinationType; // sets the format of returned value

	// Wait for Cordova to connect with the device

	//

	document.addEventListener("deviceready", onDeviceReady, false);

	// Cordova is ready to be used!

	//

	function onDeviceReady() {

		pictureSource = navigator.camera.PictureSourceType;

		destinationType = navigator.camera.DestinationType;

	}

	// Called when a photo is successfully retrieved

	//

	function onPhotoDataSuccess(imageData) {

		// Uncomment to view the base64 encoded image data

		// console.log(imageData);

		// Get image handle

		//

		var smallImage = document.getElementById('smallImage');

		// Unhide image elements

		//

		smallImage.style.display = 'block';

		// Show the captured photo

		// The inline CSS rules are used to resize the image

		//

		//smallImage.src = "data:image/jpeg;base64," + imageData;

		smallImage.src = imageData;

	}

	// Called when a photo is successfully retrieved

	//

	function onPhotoURISuccess(imageURI) {

		// Uncomment to view the image file URI

		// console.log(imageURI);

		// Get image handle

		//

		var largeImage = document.getElementById('largeImage');

		// Unhide image elements

		//

		largeImage.style.display = 'block';

		// Show the captured photo

		// The inline CSS rules are used to resize the image

		//

		//largeImage.src = "data:image/jpeg;base64," + imageData;

		largeImage.src = imageURI;

	}

	// A button will call this function

	//

	function capturePhoto() {

		// Take picture using device camera and retrieve image as base64-encoded string

		navigator.camera.getPicture(uploadPhoto, onFail, {

			quality : 50,

			destinationType : navigator.camera.DestinationType.FILE_URI,//這裏要用FILE_URI,纔會返回文件的URI地址

			//destinationType : Camera.DestinationType.DATA_URL,

			sourceType : Camera.PictureSourceType.CAMERA,

			allowEdit : true,

			encodingType : Camera.EncodingType.JPEG,

			popoverOptions : CameraPopoverOptions,

			saveToPhotoAlbum : true

		});

	}

	// A button will call this function

	//

	function capturePhotoEdit() {

		// Take picture using device camera, allow edit, and retrieve image as base64-encoded string  

		navigator.camera.getPicture(uploadPhoto, onFail, {

			quality : 50,

			allowEdit : true,

			destinationType : destinationType.DATA_URL,

			saveToPhotoAlbum : true

		});

	}

	// A button will call this function

	//

	function getPhoto(source) {

		// Retrieve image file location from specified source

		navigator.camera.getPicture(uploadPhoto, onFail, {

			quality : 50,

			destinationType : destinationType.FILE_URI,//這裏要用FILE_URI,纔會返回文件的URI地址

			sourceType : source

		});

	}

	// Called if something bad happens.

	//

	function onFail(message) {

		alert('Failed because: ' + message);

	}

	function uploadPhoto(imageURI) {

		var options = new FileUploadOptions();
		
		options.fileKey = "fileAddPic";//用於設置參數,對應form表單裏控件的name屬性,這是關鍵,廢了一天時間,徹底是由於這裏,這裏的參數名字,和表單提交的form對應

		options.fileName = imageURI.substr(imageURI.lastIndexOf('/') + 1);
		

		//若是是圖片格式,就用image/jpeg,其餘文件格式上官網查API

		options.mimeType = "image/jpeg";

		//options.mimeType = "multipart/form-data";//這兩個參數修改了,後臺就跟普通表單頁面post上傳同樣 enctype="multipart/form-data"

		//這裏的uri根據本身的需求設定,是一個接收上傳圖片的地址

		var uri = encodeURI("http://192.168.254.44:8080/MWAPI/phonegap");

		//alert(imageURI);

		//alert(uri);

		options.chunkedMode = false;
		
		/* var params = new Object();

		 params.fileAddPic = imageURI;

		 options.params = params; */

		var ft = new FileTransfer();

		ft.upload(imageURI, uri, win, fail, options);

	}

	function win(r) {

		alert("上傳成功");

		var response = r.response;

		//alert("response = " + response);

		//這裏的message是自定義的返回值,具體的根據本身的需求而定

		var message = eval("(" + r.response + ")").message;

		$("#_picFile").val(message);

		//alert("message = " + message);

		var imageURI = CONSTANT['context'] + message;

		//alert("imageURI =" + imageURI);

		onPhotoDataSuccess(imageURI);

		onPhotoURISuccess(imageURI);

		//alert("Code = " + r.responseCode);

		//alert("Response = " + r.response);

		//alert("Sent = " + r.bytesSent);

		//如下是三個默認的返回參數

		console.log("Code = " + r.responseCode);

		console.log("Response = " + r.response);

		console.log("Sent = " + r.bytesSent);

	}

	function fail(error) {

		alert("An error has occurred: Code = " + error.code);

		alert("upload error source " + error.source);

		alert("upload error target " + error.target);

		console.log("upload error source " + error.source);

		console.log("upload error target " + error.target);

	}
</script>

</head>

<body>

	<!-- page write -->

	<div data-role="page" id="write">

		<div data-role="header" data-position="fixed">

			<a href="#" data-icon="back" data-rel="back">返回</a>

			<h1>拍照並上傳圖片</h1>

			<a href="javascript:void(0);" data-icon="arrow-l" id="btn_nowsend">設置</a>

		</div>

		<!-- /header -->

		<div data-role="content">

			<input id="_picFile" type="hidden" value="" />

			<!-- take photoes -->

			<button onclick="capturePhoto();">點擊拍照</button>

			<br>

			<button onclick="getPhoto(pictureSource.PHOTOLIBRARY);">從相冊選擇圖片</button>

			<br>

			<button onclick="getPhoto(pictureSource.SAVEDPHOTOALBUM);">從相冊選擇圖片</button>

			<br> <img style="display: none; width: 120px; height: 120px;"
				id="smallImage" src="" /> <img
				style="display: none; width: 240px; height: 240px;" id="largeImage"
				src="" />

		</div>

		<!-- /content -->

		<div data-role="footer" data-position="fixed" class="ui-bar">

			<a id="btn_timingsend" href="javascript:void(0);" data-role="button"
				data-icon="plus">底部菜單</a> <a href="javascript:void(0);"
				data-role="button" data-icon="arrow-u">底部菜單</a>

		</div>

		<!-- /footer -->

	</div>

	<!-- /page write -->

</body>

</html>
服務器端接收圖片

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.tomcat.util.http.fileupload.DiskFileUpload;
import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.FileUploadException;


public class PhoneGapServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html,charset=utf-8");
		response.getWriter().println("請以POST方式上傳文件");
		System.out.println("get.........");
	}

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
//		PrintWriter out = response.getWriter();
		File file1=null;
		DiskFileUpload disFileUpload = new DiskFileUpload();
		try{
			@SuppressWarnings("unchecked")
			List<FileItem> list = disFileUpload.parseRequest(request);
			for(FileItem fileItem:list){
				if(fileItem.isFormField()){
					
				}else{
					if("fileAddPic".equals(fileItem.getFieldName())){
						File remoteFile = new File(new String(fileItem.getName().getBytes(),"UTF-8"));
						System.out.println("開始遍歷.....");

						System.out.println(fileItem.getContentType()+"----"+remoteFile.getName()+fileItem.getName());

						file1 = new File(this.getServletContext().getRealPath("attachment"),remoteFile.getName());
						file1.getParentFile().mkdirs();
						file1.createNewFile();
						
						InputStream ins = fileItem.getInputStream();
						
						OutputStream ous = new FileOutputStream(file1);
						try{
							byte[] buffer = new byte[1024];
							int len=0;
							while((len=ins.read(buffer))>-1){
								ous.write(buffer, 0, len);
							}

						}finally{
							ous.close();
							ins.close();
						}
					}
				}
			}
		}catch(FileUploadException e){
			
		}
	}

}
這樣就能夠獲取圖片了,不過HTML端獲取的圖片沒有後綴名 能夠在HTML加入下面一段代碼進行解析圖片的實際路徑

window.resolveLocalFileSystemURI(imageURI, onResolveSuccess, onError);
	   
       function onResolveSuccess(fileEntry){
    	   
			alert(fileEntry.fullPath);
		}
		function onError(error) { 

			toLog("error code: "+ error.code);

		};
HTML代碼是從網上搜到的,java代碼是最近作文件上傳,利用的apache的commons-fileupload實現的
相關文章
相關標籤/搜索