上传文件
首先前端用form表单上传文件
<!--enctype就是编码的意思,要想上传文件就要用multipart/form-data编码格式,往后端传二进制-->
<form action="/steal/upload" enctype="multipart/form-data" method="post">
<input type="file" name="file"/>
<input type="submit" value="upload"/>
</form>
后端代码
@RequestMapping("upload")
public ModelAndView upload(MultipartFile file,HttpServletRequest request,HttpServletResponse response) throws IOException {
String real=request.getServletContext().getRealPath("/upload");
String fileName=file.getOriginalFilename();
String name=fileName.substring(0,fileName.indexOf("."));
String suffix=fileName.substring(fileName.lastIndexOf("."));
//创建文件目录
//创建年月日文件夹
Calendar date=Calendar.getInstance();
File dateFile=new File(date.get(Calendar.YEAR)+File.separator+(date.get(Calendar.MONTH)+1));
//目标文件
File descFile=new File(real+File.separator+dateFile+fileName);
//如果有重名的文件
int i=1;
if(descFile.exists()){
fileName=name+"("+i+")"+suffix;
String parentPath=descFile.getParent();
descFile=new File(real+File.separator+dateFile+fileName);
i++;
}
//判断是否有此目录
if(!descFile.getParentFile().exists()){
descFile.getParentFile().mkdir();
}
try {
file.transferTo(descFile);
} catch (IOException e) {
e.printStackTrace();
}
ModelAndView model = new ModelAndView();
model.setViewName("steal/views/upload");
return model;
}
下载文件
public void down(HttpServletResponse response,HttpServletRequest request) throws IOException {
//要下载的图片地址
String path=request.getServletContext().getRealPath("/upload");
String realName="1.jpg";
//设置response响应头
response.reset();
response.setCharacterEncoding("UTF-8");
response.setContentType("multipart/from-data");
//设置响应头
response.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(realName,"UTF-8"));
File file=new File(path,realName);
//读取文件--输入流
InputStream input=new FileInputStream(file);
//写出文件--输出流
OutputStream out=response.getOutputStream();
byte[] buff=new byte[1024];
int index=0;
//执行操作
while((index=input.read(buff))!=-1){
out.write(buff,0,index);
out.flush();
}
input.close();
out.close();
}