官网文档描述如下:
Controller提供了getFile 系列方法支持文件上传。特别注意:如果客户端请求为 multipart request(form 表单使用了enctype=”multipart/form-data”),那么必须先调用 getFile 系列方法才能使 getPara 系列方法正常工作,因为 multipart request 需要通过 getFile 系列方法解析请求体中的数据,包括参数。文件默认上传至项目根路径下的upload子路径之下,该路径称为文件上传基础路径。可以在JFinalConfig.configConstant(Constants me)方法中通过 me.setBaseUploadPath(baseUploadPath)设置文件上传基础路径,该路径参数接受以”/”打头或者以 windows 磁盘盘符打头的绝对路径,即可将基础路径指向项目根径之外,方便单机多实例部署。当该路径参数设置为相对路径时,则是以项目根为基础的相对路径。
参考链接:
http://www.jfinal.com/upload/2.2/jfinal-2.2-manual.pdf
https://my.oschina.net/bloghu/blog/275289
http://www.oschina.net/question/203659_151849
下载地址:http://download.csdn.net/detail/long_1234567/3201385
默认上传路径为工程目录下”/upload”文件夹下
UploadFile files = getFile(getPara("file"));解决方法:
public void configConstant(Constants me) { //默认10M,此处设置为最大1000M me.setMaxPostSize(100*Const.DEFAULT_MAX_POST_SIZE); }参考链接:
http://blog.csdn.net/u013539342/article/details/50609648
需要用到的包和资源
js文件:
jQuery.min.js(需要jQuery的支持) ajaxfileupload.js(处理异步上传的文件)外部包:
jfinal-2.2-bin-with-src.jar(JFinal核心包) fastjson-1.2.7-sources.jar和fastjson-1.2.7.jar(用于json数据的处理) cos-26Dec2008.jar(支持JFinal自带的上传功能)html:
<!-- 上传图片 --> <input type="file" name="uploadfile" id="uploadfile"> <button id="upload" onclick="return false;">上传</button>js:
$(document).ready(function() { $('#upload').click(function() { upload($('#uploadfile').val()); }); }); function upload(fileName) { $.ajaxFileUpload({ url : '/upload', //提交的路径 secureuri : false, // 是否启用安全提交,默认为false fileElementId : 'uploadfile', // file控件id dataType : 'json', data : { fileName : fileName //传递参数,用于解析出文件名 }, // 键:值,传递文件名 success : function(data, status) { alert("上传成功"); }, error : function(data, status) { alert("上传失败"); } }); }Controller
//上传文件 public void upload(){ UploadFile uploadFile = getFile();//在磁盘上保存文件 String uploadPath = uploadFile.getUploadPath();//获取保存文件的文件夹 String fileName = uploadFile.getFileName();//获取保存文件的文件名 String filePath = uploadPath+"\\"+fileName;//保存文件的路径 String resultFileName = FileUtil.instance.changeFileName(filePath);//为了避免相同文件上传冲突,使用工具类重新命名 //也可以使用获取参数方式获取文件名 /*String filename = getPara("fileName"); filename = filename.substring(filename.lastIndexOf("\\")+1);*/ //设置返回的json JSONObject json = new JSONObject(); json.put("status", "success");//设置状态 json.put("fileName", resultFileName); renderJson(json); }FileUtil.java
public class FileUtil { public static final FileUtil instance = new FileUtil(); // 随机一个文件名 public String randomFileName() { Date dt = new Date(System.currentTimeMillis()); SimpleDateFormat sdf = new SimpleDateFormat("yyyMMddHHmmssSSS"); String fileName = sdf.format(dt); return fileName; } /** * 修改文件名 * @param filePath * eg:D:/gai.jpg * @return */ public String changeFileName(String filePath) { File file = new File(filePath);// 指定文件名及路径 String name = randomFileName() + ".xlsx"; //文件夹位置 String path = filePath.substring(0, filePath.lastIndexOf("\\")); String newFilePath = path+"\\"+name; file.renameTo(new File(newFilePath)); // 改名 return name; } }