PhoneGap 上传图片HTML和服务器端端实现(JAVA)

HTML代码  利用PhoneGap自己实现的API  FileTransfer 的 upload 代码

<!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实现的

转载于:https://my.oschina.net/u/561475/blog/104308

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值