package com.hzf.util;
import java.beans.PropertyDescriptor;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class UploadDownloadUtil {
/**
* 处理带有multipart/form-data支持文件上传的表单 Description:
*/
public String[] uploadFile(HttpServletRequest request,int diskmax,String temp,String path,int max, Affix affix) throws Exception{
System.out.println("上传中*********************************************");
List list=new ArrayList();
List itemList = new ArrayList();
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart == false)
return null;
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(diskmax);
File tempFile = new File(temp);
if (!tempFile.exists())
tempFile.mkdir();
factory.setRepository(tempFile);
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setSizeMax(max);
List items = null;
try {
items = upload.parseRequest(request);
} catch (Exception e) {
e.printStackTrace();
throw new HTMLActionException("文件大小不能超过"+max/1024/1024+"M");
}
Iterator iter = items.iterator();
// 先处理表单中的所有普通参数
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (item.isFormField()) {
processFormField(item,affix);
} else {
itemList.add(item);
}
}
// 根据不同附件实体,设置不同的上传路径
path = affix.resetPath(path);
// 处理表单中的文件参数
for(int i = 0 ;i<itemList.size();i++){
list.add(processUploadedFile(request,(FileItem)itemList.get(i),path));
}
return (String[])list.toArray(new String[list.size()]);
}
/**
* 处理表单中得普通变量 ,此时获取不到文件名称
*/
public void processFormField(FileItem item, Object obj){
String fieldName = item.getFieldName();
Class c = obj.getClass();
Field[] fs = c.getDeclaredFields();
try{
String value = new String(URLDecoder.decode(item.getString(),"utf-8"));
for(int i = 0 ; i < fs.length;i++){
if(fieldName.equals(fs[i].getName())){
PropertyDescriptor p = new PropertyDescriptor(fs[i].getName(), c);
Method m = p.getWriteMethod();
m.invoke(obj, new Object[] { CastUtil.castValue(value, fs[i].getType()) });
break;
}
}
}catch (Exception e) {
e.printStackTrace();
}
}
/**
* 处理表单中文件 Description:
*
* @param item
* @throws Exception
* @author 孙钰佳
* @param ev
* @since:Sep 3, 2007 1:06:58 PM
*/
public String processUploadedFile(HttpServletRequest request, FileItem item, String path) throws Exception {
String fileName = item.getName();
fileName = fileName.substring(fileName.lastIndexOf("\\") + 1);
System.out.println("fileName:" + fileName);
String realPath=request.getRealPath("/");
File uploadFile = new File(realPath + path);
if (!uploadFile.exists())
uploadFile.mkdirs();
String filePath = path + fileName;
File uploadedFile = new File(realPath + filePath);
item.write(uploadedFile);
return filePath;
}
/**
* @Description:文件下载
*/
public void downLoad(String filePath, HttpServletResponse response) throws Exception {
File f = new File(filePath);
if (!f.exists()) {
response.setContentType("text/html");
response.setCharacterEncoding("gbk");
PrintWriter printWriter = response.getWriter();
printWriter.println(f.getName()+"文件不存在");
printWriter.flush();
printWriter.close();
}
byte[] buf = new byte[1024];
int len = 0;
response.reset(); // 一定要重置response
response.setContentType("application/x-msdownload");
try {
response.setHeader("Content-disposition", "attachment; filename=" + new String(f.getName().getBytes("gb2312"), "iso8859-1"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
response.setHeader("Content-disposition", "attachment; filename=" + f.getName());
}
BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));
OutputStream out = response.getOutputStream();
while ((len = br.read(buf)) > 0) {
out.write(buf, 0, len);
out.flush();
}
br.close();
out.close();
}
}