本例採用plupload+commons-fileupload包實現,源碼下載地址:http://download.csdn.net/detail/lohocc/8104433
本文的代碼跟提供的源碼略有不同(根據項目需求後期進行加工改良),本文不介紹Http的斷點續傳(將在稍後的文章中進行介紹),這裏只對主要代碼做敘述
plupload下載地址:http://www.plupload.com/download/,這款插件可以支持多環境的多文件的上傳(使用方便)
1.plupload在頁面的配置
$("#uploader").pluploadQueue(
$.extend({
runtimes : runtime,//運行環境,html4,html5,flash等等,可配置多個,優先級爲從前到後
url : url,//後臺處理上傳的Action
max_file_size : max_file_size,//文件大小限制
//設置上傳字段的名稱,默認情況下被設置爲文件(file)
file_data_name : 'file',
unique_names : true,
multiple_queues : true,
rename:true,
filters : [ docFilter, imageFilter ],
flash_swf_url : 'scripts/platform/common/upload/plupload/plupload.flash.swf',//flash上傳頁面路徑
init : {
//文件上傳成功的時候觸發
FileUploaded : function(uploader, file, response) {
if (response.response) {
files.push(file.name);
}
},
//當隊列中所有文件被上傳完時觸發
UploadComplete : function(uploader, fs) {
alert("上傳完成!");
},
//上傳出錯的時候觸發
Error : function(l, o) {
var m = o.file, n;
if(m){
n = o.message;
if(o.details){
n += " (" + o.details + ")";
}
if (o.code == plupload.FILE_SIZE_ERROR) {
$.messager.alert('提示', m.name+'過大,上傳限制:'+max_file_size+'m', 'info');
}
if (o.code == plupload.FILE_EXTENSION_ERROR) {
alert("Error: Invalid file extension: "+ m.name);
}
m.hint = n;
c("#" + m.id).attr("class","plupload_failed").find("a").css("display","block").attr("title", n);
}
}
}
}, (chunk ? {//當服務端大小限制時,分段上傳
chunk_size : '1mb'
} : {})));
2.使用commons-fileupload處理上傳請求
if (ServletFileUpload.isMultipartContent(request)) {
try {
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(1024);
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("UTF-8");
upload.setSizeMax(Long.valueOf(uploadParams.get("allow-size")) * 1024 * 1024);// 設置上傳大小
List<FileItem> items = upload.parseRequest(request);
//所有文件源信息列表
List<FileUploadInfo> allFiles = new ArrayList<FileUploadInfo>();
for (FileItem item : items) {
if (!item.isFormField()) {// 如果是文件類型
String itemUploadPath = checkSaveDir(request,
item.getFieldName());
name = item.getName();// 獲得文件名
String newName = UploadUtil.generatorUUIDName().concat(".").concat(
FilenameUtils.getExtension(name));//隨機生成一個不重複的文件名
if (newName != null) {
File savedFile = new File(itemUploadPath, newName);
item.write(savedFile);//將上傳文件寫入磁盤
//這裏可以做一些自定義操作,如保留文件的詳細信息到數據庫等等
}
} else {//處理表單中其他信息,表單字段類型數據
String itemName = item.getFieldName();
String itemValue = item.getString(request.getCharacterEncoding());//這裏防止出現亂碼
parameters.put(itemName, new String[] { itemValue });
}
}
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
3.文件下載
文件下載的思路是單文件時直接下載,多文件則使用Zip流進行多文件打包下載
單文件下載:
public void downloadSingleFile(HttpServletResponse response,
FileUploadInfo fileUploadInfo) {
// 單文件下載,直接下載當前的文件
String filePath = fileUploadInfo.getFilePath();
String fileName = fileUploadInfo.getFileName();
try {
if (fileName != null && filePath != null) {
OutputStream out = response.getOutputStream();
File file = new File(filePath);
response.setContentType("application/x-download");
response.setContentLength((int)file.length());
response.addHeader(
"Content-Disposition",
"attachment;filename="
+ java.net.URLEncoder.encode(fileName, "UTF-8"));
BufferedInputStream buff = new BufferedInputStream(
new FileInputStream(file));
byte[] b = new byte[1024];
long k = 0;
// 該值用於計算當前實際下載了多少字節
// 開始循環下載
while (k < file.length()) {
int j = buff.read(b, 0, 1024);
k += j;
// 將寫入到客戶端的內存的數據,刷新到磁盤
out.write(b, 0, j);
out.flush();
}
buff.close();
out.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
多文件下載(邊壓縮邊下載):
public void downloadMultiFile(HttpServletResponse response,
List<FileUploadInfo> fileUploadInfos) {
ZipOutputStream zos = null;
try {
zos = new ZipOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
response.addHeader(
"Content-Disposition",
"attachment;filename="
+ java.net.URLEncoder.encode(
UploadUtil.getZipName(), "UTF-8"));
UploadUtil.zipFiles(fileUploadInfos, zos);
zos.flush();
zos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
zipFiles方法
<pre name="code" class="java">public static void zipFiles(List<FileUploadInfo> infoVos, ZipOutputStream zos) throws IOException {
for (FileUploadInfo info:infoVos) {
File f= new File(info.getFilePath());
zos.putNextEntry(new ZipEntry(info.getFileName()));
BufferedInputStream fis = new BufferedInputStream(new FileInputStream(f));
byte[] buffer = new byte[fis.available()];
int r = 0;
while ((r = fis.read(buffer)) != -1) {
zos.write(buffer, 0, r);
}
fis.close();
}
}
這樣一個文件上傳下載的功能就搞定了