您的位置:首页 > 其它

使用AjaxFileUploader上传图片

2012-07-27 12:59 615 查看
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
* @author  jing.yue
* @since  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"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<link type="text/css" href="${pageContext.request.contextPath}/js/jquery/ajaxFileUploader/ajaxfileupload.css" rel="stylesheet">
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery/jquery.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery/ajaxFileUploader/ajaxfileupload.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery/ajaxFileUploader/upload.js"></script>
<script type="text/javascript">
function ajaxFileUpload(_fileElementId) {
var data = {
addressAll : "${pageContext.request.contextPath}/uploadServlet",
fileElementId : _fileElementId,
success : function(_data) {
showImg(_data.filename, _data.url);
}
};
fileUpload.ajaxFileUpload(data);
}
//设置图片显示
function showImg(_filename, _url) {
alert("上传成功!");
jQuery("#showImg").attr("src", "${pageContext.request.contextPath}/" + _url);
}
</script>
</head>
<body>
<div id="wrapper">
<div id="content">
<h1>Ajax File Upload Demo</h1>
<p>Jquery File Upload Plugin  - upload your files with only one input field</p>
<p>
need any Web-based Information System?<br> Please <a href="http://www.phpletter.com/">Contact Us</a><br>
We are specialized in <br>
<ul>
<li>Website Design</li>
<li>Survey System Creation</li>
<li>E-commerce Site Development</li>
</ul>
<img id="loading" src="${pageContext.request.contextPath}/js/jquery/ajaxFileUploader/loading.gif" style="display:none;">
<form name="form" action="#" method="POST" enctype="multipart/form-data">
<table cellpadding="0" cellspacing="0" class="tableForm">
<thead>
<tr>
<th>Please select a file and click Upload button</th>
</tr>
</thead>
<tbody>
<tr>
<td><input id="fileToUpload" type="file" size="45" name="fileToUpload" class="input"></td>
</tr>
</tbody>
<tfoot>
<tr>
<td><input type="button" class="button" onclick="return ajaxFileUpload();" value="Upload" /></td>
</tr>
</tfoot>
</table>
</form>

<h3>点击图片上传做法</h3>
<label for="fileToUploadTwo">
<a href="#" onclick="fileUpload.clickUpFile({fileId:'fileToUploadTwo'});">图片</a>
<input id="fileToUploadTwo" type="file" size="45" name="fileToUploadTwo" class="input" style="display: none;" onchange="ajaxFileUpload('fileToUploadTwo');">
</label>
<img id="loadingTwo" src="${pageContext.request.contextPath}/js/jquery/ajaxFileUploader/loading.gif" style="display:none;"><br/>
</div>
<div>
<img id="showImg" alt="无" src="" width="300" height="200"/>
</div>
</div>
</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: