java最基本的文件上传和下载
上传后对上传的文件进行重新命名处理,不然上传了重复的文件会覆盖之前的文件:
/**
* 上传图片
* @param file
* @return
* @throws Exception
*/
@RequestMapping("/uploadFile")
@ResponseBody
public JsonResult uploadFile(@RequestParam(value = "file") MultipartFile file)throws Exception{
String sufferName = file.getOriginalFilename();
if (file!=null) {
//获取文件的后缀名
String subffix = sufferName.substring(sufferName.lastIndexOf(".") + 1, sufferName.length());
String path = PropertiesValue.getString("path");//文件暂时存放
File targetFile = new File(path);
if(!targetFile.isDirectory()) targetFile.mkdirs();
//对文件名进行处理
String fileName = DateUtil.formatDate(DateUtil.getTime(), "yyyyMMddHHmmss")+DateUtil.randomChar(3)+ "." + subffix;
file.transferTo(new File(path + fileName));
}
return JsonResult.success();
}
文件的下载,需对文件的后缀进行基本的定义:下载即为文件复制的过程
/**
* 下载文件
* @param name
* @param resp
* @throws Exception
*/
@RequestMapping(value = "/downFile",method = RequestMethod.GET)
public void downFile(String name, HttpServletResponse resp)throws Exception{
resp.setContentType("application/force-download");//设置响应类型
String path = "F:\\"+name;InputStream in = new FileInputStream(path);
name = URLEncoder.encode(name,"UTF-8");
resp.setHeader("Content-disposition", "attachment; filename=\"" + name + "\"");
resp.setContentLength(in.available());
//开始copy
OutputStream out = resp.getOutputStream();
byte[] b = new byte[1024];
int len = 0 ;
while((len = in.read(b))!=-1){
out.write(b,0,len);
}
out.flush();
out.close();
in.close();
}