Jfinal 文件上传

JFinal上传文件

uploadify

可以在http://www.uploadify.com/ 下载。

在原项目的基础上。

uploadify使用:


<input id="file_upload_1" name="file_upload" type="file" multiple="true">  


            /*
             * @param uploader 文件上传方法
             * @param onUploadSuccess 上传成功方法  data<String>上传成功后返回JSON数据
             */

		    $("#file_upload_1").uploadify({
		        height        : 30,
		        swf           : 'js/uploadify/uploadify.swf',
		        uploader      : 'upload/upload',
				buttonText    : '上传图片',
		        width         : 120,
		        fileSizeLimit : '500MB',
		        
				onUploadSuccess : function(file, data, response) {
					 var root = $.parseJSON(data);
					     fileRoot = root.fileRoot;
				}
		    });

more in uploadify

outPut

对应的upload方法

首先要导入jar包,cos-26Dec2008.jar这是Jfinal文件上传依赖包。

Maven地址:


<!-- https://mvnrepository.com/artifact/com.jfinal/cos -->
<dependency>
    <groupId>com.jfinal</groupId>
    <artifactId>cos</artifactId>
    <version>26Dec2008</version>
</dependency>


添加和上面对应的upload方法。

UploadController


package controller;

import java.io.File;
import java.util.List;

import com.jfinal.core.Controller;
import com.jfinal.kit.PathKit;
import com.jfinal.upload.UploadFile;

public class UploadController extends Controller {

	  /**
	   * #文件上传大小限制 10 * 1024 * 1024 = 10M
	   */
	  public static final String config_maxPostSize = "10485760";
	  /**
	   * 文件上传根路径 
	   */
	 public static final String config_fileUploadRoot = "/upload/";

	public void upload() {
		
		  /**
		   * 文件上传根路径  :我这里的PathKit.getWebRootPath():G:\eclipse-WorkSpace\JFinal_demo\WebRoot
		   */
		StringBuilder savePathStr = new StringBuilder(PathKit.getWebRootPath()+config_fileUploadRoot);
		File savePath = new File(savePathStr.toString());
		if (!savePath.exists()) {
			savePath.mkdirs();
		}
		String fileRoot="";
		try{
			// 保存文件
			List<UploadFile> files = getFiles(savePath.getPath(),Integer.parseInt(config_maxPostSize),"UTF-8");
			
			fileRoot = config_fileUploadRoot+files.get(0).getFileName();
		}catch(Exception e){
			e.printStackTrace();
		}
		setAttr("fileRoot", fileRoot);
		renderJson();

	}

}

上传图片

outPut

上传成功

outPut

上传成功后会在WebRoot生成一个upload文件。

outPut

Tips: 在文件上传表单中如果存在其他请求参数,在后端处理时,要先处理file请求,再处理其他请求参数,否则同样获取不到其他参数

源代码

兼容性问题

上传插件uploadify新版本chrome v59无法正常使用

需要在chrome://settings/content/flash ,设置flash允许网站使用flash即可。

但是这个也太麻烦了吧!!!

web uploader

我们可以用web uploader替换之 web uploader

posted @ 2018-09-17 14:35  可爱的黑精灵  阅读(5872)  评论(0编辑  收藏  举报