一:文件上传
@RequestMapping(value = "batchUpload")
public void batchUpload(HttpServletRequest req, @RequestParam("file") MultipartFile multipartFile) {
SimpleDateFormat formattime = new SimpleDateFormat("yyyyMMddHHmmss");
String time = formattime.format(new Date());
Random random = new Random();
int randomint = random.nextInt(100);
String fileId = time+String.valueOf(randomint);//id
try {
if (!multipartFile.isEmpty()) {
String name = null;// 文件名
String newFileName = null;
//String fileName = null;
//String refileName="";
String fileType="";
String uploadDir =uploadconfig.getServerPath();//文件上传地址
// 创建文件夹
File file = new File(uploadDir);
if (!file.exists()) {
file.mkdirs();
}
//处理long型主键转string防js精度丢失
name = multipartFile.getOriginalFilename();//文件名称
fileType = FilenameUtils.getExtension(name);//文件类型
newFileName = fileId.concat(".").concat(fileType); //服务器名称
String nFname = newFileName;
File savedFile = new File(uploadDir, nFname);
multipartFile.transferTo(savedFile);
}else {
}
} catch (Exception e) {
e.printStackTrace();
}
}
二:文件下载
@RequestMapping(value="/downloadFile")
public void downloadFile(String pathname,String ServerName,HttpServletResponse response,HttpServletRequest request) throws Exception {
String dir = uploadconfig.getServerPath();//下载地址
String path = dir+"/"+pathname; //下载地址+名称
System.out.println("这是下载地址加名称------------:"+path);
File file=new File(path);
boolean exists = file.exists();
System.out.println("是否有该文件:"+exists);
if (exists) {
response.setCharacterEncoding("utf-8");
response.setContentType("text/plain");
//解决中文乱码
try {
response.setHeader("Content-Disposition","attachment;filename="+new String("下载后的名称".getBytes("utf-8"),"iso-8859-1"));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// FileInputStream fis=new FileInputStream(file);
// BufferedInputStream buff=new BufferedInputStream(fis);
InputStream in = new FileInputStream(file);
ServletOutputStream os = response.getOutputStream();
int len;
byte [] b=new byte[1024];//
while((len=in.read(b))!=-1){
os.write(b,0,len);
}
os.close();
in.close();
}else {
System.out.println("该路径下没有该文件:"+path);
}
}
笔记!勿喷