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

Posted 白夜鸦羽

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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

以上是关于JFinal+ajaxfileupload实现图片的异步上传的主要内容,如果未能解决你的问题,请参考以下文章

ajaxfileupload.js实现无刷新异步上传图片Demo

JQuery的ajaxFileUpload图片上传初试

ajaxfileupload

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

jsp中使用jquery的ajaxfileupload插件怎么实现异步上传

基于jifnal框架的文件上传一般形式(img)