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
点击图片上传做法