工具类文件上传与下载代码

来源:互联网 发布:淘宝企业店铺扶持 编辑:程序博客网 时间:2024/05/16 10:17
一、工具类文件上传与下载代码:
public class FileOperateUtil {


private static final String REALNAME = "realName";
private static final String STORENAME = "storeName";
private static final String SIZE = "size";
private static final String SUFFIX = "suffix";
private static final String CONTENTTYPE = "contentType";
private static final String CREATETIME = "createTime";
private static final String UPLOADDIR = "fileUpload/";


/**
* 将上传的文件进行重命名,这个功能可以适当的取舍,文件上传上去后可以就按照原文名保存。所有文件都是以压缩文件的形式保存的;
* 若本身就是压缩则不再压缩。

*/
private static String rename(String name) {
Long now = Long.parseLong(new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())); Long random = (long) (Math.random() * now);
String fileName = now + "" + random;
String fileName = name;
if (name.indexOf(".") != -1) {
fileName += name.substring(name.lastIndexOf("."));
}
return fileName;
}


/**
* 文件上传被压缩后的文件名
*/
private static String zipName(String name) {
String prefix = "";
if (name.indexOf(".") != -1) {
prefix = name.substring(0, name.lastIndexOf("."));
} else {
prefix = name;
}
//判断上传文件是否为压缩,如果为压缩,则直接上传
if(name.endsWith(".rar")||name.endsWith(".zip"))
return prefix;
else
return prefix + ".zip";
}


/**
* 上传文件类

*/
public static List<Map<String, Object>> upload(HttpServletRequest request,
String[] params, Map<String, Object[]> values) throws Exception {


List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();


MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;
Map<String, MultipartFile> fileMap = mRequest.getFileMap();


String uploadDir = request.getSession().getServletContext()
.getRealPath("/")
+ FileOperateUtil.UPLOADDIR;
File file = new File(uploadDir);


if (!file.exists()) {
file.mkdir();
}


String fileName = null;
int i = 0;
for (Iterator<Map.Entry<String, MultipartFile>> it = fileMap.entrySet()
.iterator(); it.hasNext(); i++) {


Map.Entry<String, MultipartFile> entry = it.next();
MultipartFile mFile = entry.getValue();


fileName = mFile.getOriginalFilename();


String storeName = rename(fileName);
String noZipName = uploadDir + storeName;
String zipName = zipName(noZipName);


// 上传成为压缩文件
ZipOutputStream outputStream = new ZipOutputStream(
new BufferedOutputStream(new FileOutputStream(zipName)));
outputStream.putNextEntry(new ZipEntry(fileName));
outputStream.setEncoding("GBK");
FileCopyUtils.copy(mFile.getInputStream(), outputStream);
Map<String, Object> map = new HashMap<String, Object>();
// 固定参数值对
map.put(FileOperateUtil.REALNAME, fileName);
// map.put(FileOperateUtil.REALNAME, zipName(fileName));
map.put(FileOperateUtil.STORENAME, zipName(storeName));
// map.put(FileOperateUtil.SIZE, new File(zipName).length());
// map.put(FileOperateUtil.SUFFIX, "zip");
// map.put(FileOperateUtil.CONTENTTYPE, "application/octet-stream");
// map.put(FileOperateUtil.CREATETIME, new Date());


// 自定义参数值对
/*
* for (String param : params) { map.put(param,
* values.get(param)[i]); }
*/


result.add(map);
}
return result;
}


/**
* 文件下载类

*/
public static void download(HttpServletRequest request,
HttpServletResponse response, String storeName, String contentType)
throws Exception {
response.setContentType(contentType);
request.setCharacterEncoding("UTF-8");
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
String ctxPath = request.getSession().getServletContext()
.getRealPath("/")
+ FileOperateUtil.UPLOADDIR;
String downLoadPath = ctxPath + storeName;
long fileLength = new File(downLoadPath).length();
response.setHeader("Content-disposition", "attachment; filename="
+ new String(storeName.getBytes("UTF-8"), "ISO-8859-1"));
response.setHeader("Content-Length", String.valueOf(fileLength));
bis = new BufferedInputStream(new FileInputStream(downLoadPath));
bos = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
bis.close();
bos.close();
}


}








二、控制层代码:




/**
* 增加公文,并且将文件压缩上传到服务器中的fileUpload文件中
* @param gongwen
* @param request
* @return
* @throws Exception
*/
public String addGongWen(GongWen gongwen, HttpServletRequest request) throws Exception{


Map<String, Object> map = new HashMap<String, Object>();
// 别名
String[] alaises = ServletRequestUtils.getStringParameters(request,"alais");
String[] params = new String[] { "alais" };
Map<String, Object[]> values = new HashMap<String, Object[]>();
values.put("alais", alaises);
List<Map<String, Object>> result = FileOperateUtil.upload(request,
params, values);
gwService.addGongWen(gongwen,result);
return "/GongWen/getAllGongWen";
}

/**
* 公文下载,文件下载下来也是压缩文件,文件名为:原文件名+文件类型.zip
* @param request
* @param response
* @param storeName
* @return
* @throws Exception
*/
@RequestMapping(value = "/download")
public ModelAndView download(HttpServletRequest request,
HttpServletResponse response,String storeName) throws Exception {
System.out.println(storeName);
String contentType = "application/octet-stream";
FileOperateUtil.download(request, response, storeName, contentType);
return null;
}


/**
* 删除文件
*/

public void delGongWen(String gwid,String storeName, HttpServletResponse response,HttpServletRequest request) {
String result = "{\"result\":\"error\"}";
String delPath=FileOperateUtil.getPath(request, storeName);
File file = new File(delPath);
if (file.isFile() && file.exists()) {  
    file.delete(); 
}  
/*
if (gwService.delGongWen(gwid)) {
result = "{\"result\":\"success\"}";
}
response.setContentType("application/json");


try {
PrintWriter out = response.getWriter();
out.write(result);
} catch (IOException e) {
e.printStackTrace();
}*/
}
1 0