上传 与下载
package org.wanda.work.controller;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.ModelAndView;
import org.wanda.work.service.FileService;
import org.wanda.work.util.FileCharsetDetector;
import org.wanda.work.util.MD5Utils;
import com.alibaba.fastjson.JSONObject;
/**
* 资料上传
*
* @author wxf
*
*/
@Controller
@RequestMapping("/multipart-file")
public class FileUploadController {
/**
* 自动注入
*/
@Autowired
public FileService FileService;
private static String filepath;
private static String uploadFileUrlPrefix;
public String getFilepath() {
return filepath;
}
@Value("#{configProperties['upload.file.path.root']}")
public void setFilepath(String filepath) {
this.filepath = filepath;
}
@Value("#{configProperties['upload.file.url.prefix']}")
public void setUploadFileUrlPrefix(String uploadFileUrlPrefix) {
this.uploadFileUrlPrefix = uploadFileUrlPrefix;
}
@ResponseBody
@RequestMapping("/upload.do")
public Object upload(HttpServletRequest request, HttpServletResponse response)
throws IllegalStateException, IOException {
JSONObject data = new JSONObject();
Map<String, Object> result = new HashMap<String, Object>();
// 创建一个通用的多部分解析器
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
request.getSession().getServletContext());
// 判断 request 是否有文件上传,即多部分请求
if (multipartResolver.isMultipart(request)) {
// 转换成多部分request
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
// 取得request中的所有文件名
Iterator<String> iter = multiRequest.getFileNames();
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);//获取年份
int month=cal.get(Calendar.MONTH)+1;//获取月份
int day=cal.get(Calendar.DATE);//获取日
int hour=cal.get(Calendar.HOUR);//小时
int minute=cal.get(Calendar.MINUTE);//分
int second=cal.get(Calendar.SECOND);//秒
while (iter.hasNext()) {
// 取得上传文件
MultipartFile file = multiRequest.getFile(iter.next());
if (file != null) {
// 取得当前上传文件的文件名称
String myFileName = file.getOriginalFilename();
// 如果名称不为“”,说明该文件存在,否则说明该文件不存在
if (myFileName.trim() != "") {
String fileName = file.getOriginalFilename();// 重命名上传后的文件名
String newfileName = ""; // 最新的文件名
if ((fileName != null) && (fileName.length() > 0)) {
int dot = fileName.indexOf('.');
if ((dot > -1) && (dot < (fileName.length()))) {
newfileName = fileName.substring(0, fileName.indexOf("."));
}
}
String extName = ""; // 后缀
if ((fileName != null) && (fileName.length() > 0)) {
int dot = fileName.lastIndexOf('.');
if ((dot > -1) && (dot < (fileName.length()))) {
extName = fileName.substring(fileName.lastIndexOf(".") + 1);
}
}
// 定义上传路径
String path = "";
if (extName.equals("")) {
path = year + "/" + month + "/" + day +"/"+ hour+minute+second+MD5Utils.GetMD5Code(newfileName);
} else {
path = year + "/" + month + "/" + day +"/"+ hour+minute+second+ MD5Utils.GetMD5Code(newfileName) + "."
+ extName;
}
String path2 = uploadFileUrlPrefix + "/" +year + "/" + month + "/" + day +"/"+ hour+minute+second+MD5Utils.GetMD5Code(newfileName) + "." + extName;
// 如果文件夹没有,则创建
getfile(filepath + "/" + year + "/" + month + "/" + day);
File localFile = new File(filepath + "/" + path);
// if (!localFile.exists() && !localFile.isFile()) {
// 上传文件
file.transferTo(localFile);
String extName2=extName.toLowerCase();
if ("pdf".equals(extName2) || "word".equals(extName2) || "doc".equals(extName2)
|| "jpg".equals(extName2) || "dll".equals(extName2) || "excel".equals(extName2)||"wps".equals(extName2)||
"ppt".equals(extName2)||"exe".equals(extName2) ||"dot".equals(extName2) ||"xls".equals(extName2)||"com".equals(extName2)||"bat".equals(extName2) ){
}else{
String encoding = new FileCharsetDetector().guestFileEncoding(new FileInputStream(localFile));
if (StringUtils.isNotBlank(encoding)) {
String content = FileUtils.readFileToString(localFile, encoding);
FileUtils.writeStringToFile(localFile, content, "utf-8");
}
}
if("pdf".equals(extName.toLowerCase())||"txt".equals(extName.toLowerCase())||"jpg".equals(extName.toLowerCase())||"html".equals(extName.toLowerCase())){
result.put("filepath",path2);// 文件url
}else{
result.put("filepath","");// 文件url
}
// 返回前台数据 存map
result.put("name", fileName);
result.put("newfileName", newfileName);
result.put("url", path);
// 返回前台数据 存json
data.put("resultcode", 200);
data.put("reason", "上传文件成功");
data.put("result", result);
return data;
// }
// } else {
// result.put("name", fileName);
// result.put("newfileName", newfileName);
// result.put("url", path);
// result.put("filepath",path2);
// data.put("result", result);
// //返回前台数据 存json
// data.put("resultcode", 201);
// data.put("reason", "上传文件成功");
// return data;
// }
}
}
}
}
data.put("resultcode", 201);
data.put("reason", "上传文件失败,请重新上传");
return data;
}
public void getfile(String filepath) {
File yearfile = new File(filepath);
// 如果文件夹不存在则创建
if (!yearfile.exists() && !yearfile.isDirectory()) {
yearfile.mkdirs();
}
}
/**
* 下载
*
*/
@RequestMapping(value = "/download.do")
public ModelAndView download(HttpServletRequest request,
HttpServletResponse response,String path,String name) throws Exception {
download(request, response, path, "application/octet-stream",
name);
return null;
}
public static void download(HttpServletRequest request,
HttpServletResponse response, String storeName, String contentType,
String realName) throws Exception {
response.setContentType("text/html;charset=UTF-8");
request.setCharacterEncoding("UTF-8");
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
String downLoadPath = filepath + storeName;
long fileLength = new File(downLoadPath).length();
response.setContentType(contentType);
response.setHeader("Content-disposition", "attachment; filename="
+ new String(realName.getBytes("utf-8"), "ISO8859-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();
}
}