JFinal+ajaxfileupload实现图片的异步上传

需要用到的包和资源

js文件:
jquery.min.js(需要jQuery的支持)
ajaxfileupload.js(处理异步上传的文件)

外部包:
jfinal-2.0-bin-with-src.jar(JFinal核心包)
fastjson-1.2.7-sources.jar和fastjson-1.2.7.jar(用于json数据的处理)
cos-26Dec2008.jar(支持JFinal自带的上传功能)

源代码说明

上传的JSP页面代码

<!-- 上传图片 -->
<input type="file" name="image" id="imageFile">
<button id="upload" onclick="return false;">上传</button>
<!-- 存储图片地址,并显示图片 -->
<input type="hidden" name="pictureSrc" id="pictureSrc">
<div id="show"></div>

<!-- 图片上传js文件,放到最后加载 -->
<script type="text/javascript" src="${contextPath}/js/jquery.min.js"></script>
<script type="text/javascript" src="${contextPath}/js/ajaxfileupload.js"></script>
<script type="text/javascript" src="${contextPath}/js/upload.js"></script>

在页面上导入jquery.min.js和ajaxfileupload.js两个文件,upload.js文件是用来来提交数据和上传文件,并接收服务器回发的json数据

upload.js源代码

$(document).ready(function() {
	$('#upload').click(function() {
		upload($('#imageFile').val());   //函数参数为上传的文件的本机地址
	});
});

function upload(fileName) {
	$.ajaxFileUpload({
		url : 'upload/imageUpload',   //提交的路径
		secureuri : false, // 是否启用安全提交,默认为false
		fileElementId : 'imageFile', // file控件id
		dataType : 'json',
		data : {
			fileName : fileName   //传递参数,用于解析出文件名
		}, // 键:值,传递文件名
		success : function(data, status) {
			if (data.error == 0) {
				var src = data.src;
				$('#show').append("<img src='" + src + "'>");  //显示图片

				// 存储已上传图片地址
				var oldSrc = $('#pictureSrc').val();
				var newSrc = "";
				if (oldSrc != "")
					newSrc = oldSrc + ";" + src;
				else
					newSrc = src;

				$('#pictureSrc').val(newSrc);   //保存路径
			} else {
				alert(data.message);
			}
		},
		error : function(data, status) {
			alert(data.message);
		}
	});
}

一次上传一张图片,可多次上传。上传成功后,将图片显示在页面上,并将图片地址存放在type=“hidden"的input标签中,并按”;"来分隔图片地址

用于处理的controller文件UploadController.java文件代码

public void imageUpload() {
	UploadFile uploadFile = getFile("imgFile", PathKit.getWebRootPath()
			+ "/temp", 20 * 1024 * 1024, "utf-8"); // 最大上传20M的图片
	// 异步上传时,无法通过uploadFile.getFileName()获取文件名
	String fileName = getPara("fileName");
	fileName = fileName.substring(fileName.lastIndexOf("\\") + 1); // 去掉路径

	// 异步上传时,无法通过File source = uploadFile.getFile();获取文件
	File source = new File(PathKit.getWebRootPath() + "/temp/" + fileName); // 获取临时文件对象

	String extension = fileName.substring(fileName.lastIndexOf("."));
	String savePath = PathKit.getWebRootPath() + "/upload/images/"
			+ CommonUtils.getCurrentDate();
	JSONObject json = new JSONObject();

	if (".png".equals(extension) || ".jpg".equals(extension)
			|| ".gif".equals(extension) || "jpeg".equals(extension)
			|| "bmp".equals(extension)) {
		fileName = CommonUtils.getCurrentTime() + extension;

		try {
			FileInputStream fis = new FileInputStream(source);

			File targetDir = new File(savePath);
			if (!targetDir.exists()) {
				targetDir.mkdirs();
			}

			File target = new File(targetDir, fileName);
			if (!target.exists()) {
				target.createNewFile();
			}

			FileOutputStream fos = new FileOutputStream(target);
			byte[] bts = new byte[1024 * 20];
			while (fis.read(bts, 0, 1024 * 20) != -1) {
				fos.write(bts, 0, 1024 * 20);
			}

			fos.close();
			fis.close();
			json.put("error", 0);
			json.put("src", "upload/images/" + CommonUtils.getCurrentDate()
					+ "/" + fileName); // 相对地址,显示图片用
			source.delete();

		} catch (FileNotFoundException e) {
			json.put("error", 1);
			json.put("message", "上传出现错误,请稍后再上传");
		} catch (IOException e) {
			json.put("error", 1);
			json.put("message", "文件写入服务器出现错误,请稍后再上传");
		}
	} else {
		source.delete();
		json.put("error", 1);
		json.put("message", "只允许上传png,jpg,jpeg,gif,bmp类型的图片文件");
	}

	renderJson(json.toJSONString());
}

先通过JFinal自带的文件上传类UploadFile,将文件上传到项目根目录下面的temp文件夹下面,临时保存起来。
又因为异步上传时,无法通过uploadFile.getFile();直接获取文件进而对文件进行后续操作,故先通过获取临时文件文件名,进而获取该临时文件对象,再对该文件进行操作,如下代码

String fileName = getPara("fileName");
fileName = fileName.substring(fileName.lastIndexOf("\\") + 1); // 去掉路径

// 异步上传时,无法通过File source = uploadFile.getFile();获取文件
File source = new File(PathKit.getWebRootPath() + "/temp/" + fileName); // 获取临时文件对象

后面将文件名和后缀名分隔开,判断是否为图片文件:若不是,则删除临时文件,拒绝上传并返回报错的json数据;若是,则复制上传的临时文件,并重命名放入指定文件夹下,删除上传的临时文件。其中,CommonUtils为工具类,主要获取当前日期和时间,代码如下

package org.dny.utils;

import java.text.SimpleDateFormat;
import java.util.Date;

public class CommonUtils {
	/** 默认的格式化方式 */
	private static final String defaultFormat = "yyyy-MM-dd HH:mm:ss";

	public static String getDate() {
		SimpleDateFormat dateFormat = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss");
		Date currentDate = new Date();
		String formatCurrentDate = dateFormat.format(currentDate).toString();

		return formatCurrentDate;
	}

	public static String getCurrentDate() {
		String format = "yyyy-MM-dd";
		Date date = new Date();
		date.setTime(System.currentTimeMillis());
		if (format == null || "".equals(format.trim())) {
			format = defaultFormat;
		}
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		return sdf.format(date);
	}

	public static String getCurrentTime() {
		String format = "yyyyMMddHHmmss";
		Date date = new Date();
		date.setTime(System.currentTimeMillis());
		if (format == null || "".equals(format.trim())) {
			format = defaultFormat;
		}
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		return sdf.format(date);
	}
}

运行结果

这里写图片描述

项目包下载

项目包下载地址:
http://download.csdn.net/detail/u013539342/9422743
下载后导入MyEclipse 2014可直接运行

参考地址

感谢前辈们的付出,我只是个搬运工+扩展者
参考地址:
http://www.cnblogs.com/kissdodog/archive/2012/12/15/2819025.html
http://www.oschina.net/code/snippet_2255303_43121

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值