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
對應的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();
}
}
上傳圖片
上傳成功
上傳成功后會在WebRoot生成一個upload文件。
Tips: 在文件上傳表單中如果存在其他請求參數,在后端處理時,要先處理
file
請求,再處理其他請求參數,否則同樣獲取不到其他參數
兼容性問題
上傳插件uploadify
新版本chrome v59
無法正常使用
需要在chrome://settings/content/flash
,設置flash
允許網站使用flash即可。
但是這個也太麻煩了吧!!!
web uploader
我們可以用web uploader
替換之 web uploader