(1)文件的上传
@RequestMapping(value="/uploadFile",method=RequestMethod.POST)
public void uploadFile(MultipartFile myfile,HttpServletRequest req){
String fileName=myfile.getOriginalFilename();
name=fileName;
System.out.println(fileName);
//设置保存的路径
String realPath=req.getServletContext().getRealPath("/uploadFiles");
//保存文件的全路径
File file=new File(realPath,fileName);
if(!file.getParentFile().exists()){
file.getParentFile().mkdirs();
}
System.out.println("文件路径");
System.out.println(file.getPath());
try {
// IOUtils.copy(myfile.getInputStream(), new FileOutputStream(file));这种可以上传文件
myfile.transferTo(file);//文件上传的方法
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
(2)文件的下载
@RequestMapping(value="/download",method=RequestMethod.GET)
public ResponseEntity download(HttpServletRequest req,HttpServletResponse resp) throws Exception {
resp.setCharacterEncoding("utf-8");
req.setCharacterEncoding("utf-8");
//用来封装响应头的信息
HttpHeaders responseHeaders=new HttpHeaders();
//下载的附件类型
responseHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
//下载的附件名称,存在数据库中原始的文件名
String fileName=new String("aop的配置.docx".getBytes("utf-8"),"iso-8859-1");
//告诉响应头这是一个附件
responseHeaders.setContentDispositionFormData("attachment", fileName);
//到目录下找要下载的附件
String path=req.getServletContext().getRealPath("uploadFiles");
//目录下存在的文件名
String fname="aop的配置.docx";
//将下载的文件封装流对象
File file=new File(path,fname);
try{
return new ResponseEntity(FileUtils.readFileToByteArray(file),responseHeaders,HttpStatus.CREATED);
}catch(Exception e){
e.printStackTrace();
}
return null;
}