PhoneGap 文件上传(Java 后台代码)

来源:互联网 发布:淘宝退款骗局揭秘 编辑:程序博客网 时间:2024/06/11 08:43
今天用phoneGap做IOS照片上传,网上收了很久,未找到Java后台接受上传图片代码
看到这篇文章后,受到启发:http://blog.csdn.net/xiaoguang44/article/details/8073915

附Java后台接受源码:
采用commons-fileupload-1.2.1.jar接收

public class FileUpload extends HttpServlet {/** *  */private static final long serialVersionUID = 1L;@Overrideprotected void service(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {// TODO Auto-generated method stub//获取工程根目录String rootPath = req.getRealPath("/WEB-INF");//临时存储路径File tempFile = new File(rootPath + "/Temp");if(!tempFile.exists()){tempFile.mkdirs();}//是否是文件上传boolean isMultipart = ServletFileUpload.isMultipartContent(req);if (isMultipart) {try {// 创建磁盘工厂,利用构造器实现内存数据储存量和临时储存路径DiskFileItemFactory factory = new DiskFileItemFactory(1024 * 4,tempFile);// 设置最多只允许在内存中存储的数据,单位:字节// factory.setSizeThreshold(4096);// 设置文件临时存储路径// factory.setRepository(new File("D:\\Temp"));// 产生一新的文件上传处理程式ServletFileUpload upload = new ServletFileUpload(factory);// 设置路径、文件名的字符集upload.setHeaderEncoding("UTF-8");// 设置允许用户上传文件大小,单位:字节upload.setSizeMax(1024 * 1024 * 100);// 解析请求,开始读取数据// Iterator<FileItem> iter = (Iterator<FileItem>)// upload.getItemIterator(request);// 得到所有的表单域,它们目前都被当作FileItemList<FileItem> fileItems = upload.parseRequest(req);// 依次处理请求Iterator<FileItem> iter = fileItems.iterator();while (iter.hasNext()) {FileItem item = (FileItem) iter.next();if (item.isFormField()) {// 如果item是正常的表单域String name = item.getFieldName();String value = item.getString("UTF-8");System.out.println("表单域名为:" + name + "表单域值为:" + value);} else {// 如果item是文件上传表单域// 获得文件名及路径String fileName = item.getName();if (fileName != null) {// 如果文件存在则上传File fullFile = new File(item.getName());if (!fullFile.exists()) {//真实路径String realSavePath = makeDir(rootPath + "/img");//判断是否存在,不存在,则创建if(realSavePath == null){System.out.println("文件目录创建失败!");return;}File fileOnServer = new File(realSavePath +"/"+fullFile.getName());item.write(fileOnServer);System.out.println("文件"+ fileOnServer.getName() + "上传成功");}}}}} catch (Exception e) {e.printStackTrace();}}}/** *  组装文件目录,并创建文件目录 *   * @param savePath 存储路径 * @return String 文件目录 */private String makeDir(String savePath){DateFormat sf = new SimpleDateFormat("yyyy-MM-dd");String dateStr = sf.format(new Date());String saveDirectory = savePath + "/" + dateStr;File file = new File(saveDirectory);if(!file.exists()){if(file.mkdirs()){return saveDirectory;}else{return null;}}else{return saveDirectory;}}}

附前台js代码:

var options = new FileUploadOptions();                                    options.fileKey = "fileAddPic";//用于设置参数,对应form表单里控件的name属性,这是关键,废了一天时间,完全是因为这里,这里的参数名字,和表单提交的form对应                                    var imagefilename = Number(new Date())+".jpg";                  options.fileName = imagefilename;                  //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 url = encodeURI("http://192.168.2.9:8080/oper-ui/fileUpload");                                    //alert(imageURI);                                    //alert(uri);                                      options.chunkedMode = false;                                      var params = new Object();                                      params.fileAddPic = path;  //path 是图片手机客户端保存路径                                    options.params = params;                                       var ft = new FileTransfer();                                      ft.upload(path, url,                            function(result) {                                    console.log('Upload success: ' + result.responseCode);                                    console.log(result.bytesSent + ' bytes sent');                        },                            function(error) {                                    console.log('Error uploading file ' + path + ': ' + error.code);                        },                        options);
测试~通过!大笑

原创粉丝点击