博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
使用AjaxFileUploader上传图片
阅读量:6165 次
发布时间:2019-06-21

本文共 7749 字,大约阅读时间需要 25 分钟。

hot3.png

AjaxFileUploader是一款基于jQuery实现的上传文件的组建。其实AjaxFileUploader的机制是基于ifrarme的上传来实现无页面刷新的。

下面讲解下怎么使用。

java代码[这里也可以换成其它语言的]:

package com.jing.servlets;import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.util.Date;import java.util.regex.Matcher;import java.util.regex.Pattern;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.commons.fileupload.FileItemIterator;import org.apache.commons.fileupload.FileItemStream;import org.apache.commons.fileupload.disk.DiskFileItemFactory;import org.apache.commons.fileupload.servlet.ServletFileUpload;import org.apache.commons.fileupload.util.Streams;import org.apache.log4j.Logger;/** * 附件上传servlet *   jing.yue *   2012-07-26 * @version 1.0.0 */public class UploadServlet extends HttpServlet {	private static final long serialVersionUID = 7480621143378258586L;	private static final Logger logger = Logger.getLogger(UploadServlet.class);	// 字符集编码	private static String encoding = "UTF-8";	public void init() throws ServletException {		super.init();	}	/**	 * doGet	 *	 * @param request	 * @param res	 * @param session	 * @throws ServletException	 * @throws IOException	 */	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {		doPost(request, response);	}	/**	 * doPost	 *	 * @param request	 * @param reponse	 * @throws ServletException ,	 *             IOException	 */	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {		//指定的文件名称		String paramFileName = request.getParameter("fileName");		response.setContentType("text/html");		response.setCharacterEncoding(encoding);		String realDir = request.getSession().getServletContext().getRealPath("");		String contextpath = request.getContextPath();		String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + contextpath + "/";		try {			String filePath = "upload_images/poster";			String realPath = realDir + "\\" + filePath;			//判断路径是否存在,不存在则创建			File dir = new File(realPath);			if(!dir.isDirectory())				dir.mkdirs();			if(ServletFileUpload.isMultipartContent(request)){				DiskFileItemFactory dff = new DiskFileItemFactory();				dff.setRepository(dir);				dff.setSizeThreshold(1024000);				ServletFileUpload sfu = new ServletFileUpload(dff);				FileItemIterator fii = null;				fii = sfu.getItemIterator(request);				//图片标题				String title = "";				//图片地址				String url = "";				String fileName = "";				String msg = "";				String error = "";				String realFileName="";				while(fii.hasNext()){					FileItemStream fis = fii.next();					try{						if(!fis.isFormField() && fis.getName().length()>0){							fileName = fis.getName();							Pattern reg=Pattern.compile("[.]jpg|png|jpeg|gif$");							Matcher matcher=reg.matcher(fileName);							if(!matcher.find()) {								error = "文件类型不允许!";								break;							}							//文件名称							if(paramFileName == null || "".equals(paramFileName.trim())) {								realFileName = new Date().getTime() + fileName.substring(fileName.lastIndexOf("."), fileName.length());							} else {								realFileName = paramFileName;							}							url = realPath + "\\" + realFileName;							//获得文件输入流							BufferedInputStream in = new BufferedInputStream(fis.openStream());							FileOutputStream a = new FileOutputStream(new File(url));							BufferedOutputStream output = new BufferedOutputStream(a);							//开始把文件写到你指定的上传文件夹							Streams.copy(in, output, true);						}else{							String fname = fis.getFieldName();							if(fname.indexOf("pictitle")!=-1){								BufferedInputStream in = new BufferedInputStream(fis.openStream());								byte c [] = new byte[10];								int n = 0;								while((n=in.read(c))!=-1){									title = new String(c,0,n);									break;								}							}						}						if(fileName == null || "".equals(fileName.trim())) {							error = "请选择文件!";							break;						} else {							msg = "上传成功!";						}					}catch(Exception e){						e.printStackTrace();						error = "上传文件异常!";					}				}				response.setStatus(200);				StringBuffer result = new StringBuffer();				result.append("{filename:'" + realFileName + "',");				result.append("title:'" + title + "',");				result.append("src:'" + basePath + filePath + "/" + realFileName + "',");				result.append("url:'" + filePath + "/" + realFileName + "',");				result.append("msg:'" + msg + "',");				result.append("error:'" + error + "'}");				logger.info("response: " + result.toString());				response.getWriter().print(result.toString());			}		}catch(Exception ee) {			ee.printStackTrace();		}	}}

自己封装的upload.js

//=======================================================================//		功能: 		上传文件的工具类//		author:		岳静//		e-mail: 	yuejing0129@126.com//		QQ:			503490146//		date: 		2012-07-26//		version: 	1.0//=======================================================================var fileUpload = {		/**		 * 触发上传图片按钮点击事件		 * @param _data : json类型的参数		 *  _data.fileId : file控件的ID名称[不传默认为'fileToUpload']		 */		clickUpFile : function(_data) {			if(_data == undefined) {				_data = {};			}			if(_data.fileId == undefined) {				_data.fileId = "fileToUpload";			}			//不为IE			if(navigator.userAgent.indexOf("MSIE") <= 0) {				jQuery("#" + _data.fileId).click();			}		},		/**		 * 上传图片		 * @param _data : 传入的参数[为json]		 *  _data.address : 项目根目录地址[如: /weibo, 默认为'/weibo']		 *  _data.addressAll : 上传图片的完整地址[默认为'/weibo/uploadServlet']		 *  _data.fileElementId : 上传图片的file的ID名称[不传默认为'fileToUpload']		 *  _data.loading : 加载中图片显示的ID[不传默认为'loading']		 *  _data.param : 传入后台的参数的json		 *  _data.success : 执行成功的回调函数[回调函数内有JSON类型的值]		 * @returns		 */		ajaxFileUpload : function(_data) {			if(_data.fileElementId == undefined) {				_data.fileElementId = 'fileToUpload';			}			if(_data.param == undefined) {				_data.param = {};			}			if(_data.address == undefined) {				_data.address = "/weibo";			}			if(_data.loading == undefined) {				_data.loading = "loading";			}			if(_data.addressAll == undefined) {				_data.addressAll = _data.address + "/uploadServlet";			}			jQuery("#" + _data.loading)			.ajaxStart(function(){				jQuery(this).show();			})			.ajaxComplete(function(){				jQuery(this).hide();			});			jQuery.ajaxFileUpload({				url: _data.addressAll,				secureuri:false,				fileElementId: _data.fileElementId,				dataType: 'json',				data: _data.param,				success: function (data, status) {					if(typeof(data.error) != 'undefined') {						//出现异常						if(data.error != '') {							alert(data.error);						}						//上传成功						else if(data.msg != '') {							_data.success(data);						}					}				},				error: function (data, status, e) {					alert(e);				}			});			return false;		}};

jsp或html代码[这里需要我们引入jQuery.js、upload.js和AjaxFileUploader.js文件]:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
Insert title here

Ajax File Upload Demo

Jquery File Upload Plugin - upload your files with only one input field

need any Web-based Information System?

Please Contact Us
We are specialized in

  • Website Design
  • Survey System Creation
  • E-commerce Site Development
Please select a file and click Upload button

点击图片上传做法

无

转载于:https://my.oschina.net/castusz/blog/69358

你可能感兴趣的文章
书籍列表
查看>>
scrollview 例子2
查看>>
20165211 2017-2018-2 《Java程序设计》课程总结
查看>>
C# 截取字符串某个字符分割的最后一部分
查看>>
css2选择器
查看>>
Selenium Chrome浏览器的启动以及proxy设置
查看>>
uCOS-II+LwIP+DM9000(源代码)
查看>>
BZOJ3172:[TJOI2013]单词——题解
查看>>
洛谷4643:【模板】动态dp——题解
查看>>
python三大神器之virtualenv pip, virtualenv, fabric通称为pythoner的三大神器。
查看>>
MPMoviePlayerController播放视频
查看>>
java批量解压文件夹下的所有压缩文件(.rar、.zip、.gz、.tar.gz)
查看>>
[转] Transformer
查看>>
回溯法--装载问题
查看>>
HTML中的GroupBox
查看>>
Python入门-----Windows安装
查看>>
【java】TreeMap/HashMap的循环迭代中 keySet和entrySet和forEach方式 + map的几种迭代方式...
查看>>
【hibernate/JPA】注解方式实现 复合主键【spring boot】
查看>>
【linux】linux下对java程序生成dump文件,并使用IBM Heap Analyzer进行分析,查找定位内存泄漏的问题代码...
查看>>
C++ isalpha、isalnum、islower、isupper用法
查看>>