1,文件上传
@RequestMapping("addattachment")
public String addattachment(@RequestParam(value = "pid",required = false) String pid,
@RequestParam(value = "attname",required = false) String attname,
@RequestParam(value = "attdis",required = false) String attdis,
@RequestParam(value = "remark",required = false) String remark,
@RequestParam("fileUpload")MultipartFile multipartFile
){
Attachment a =new Attachment();
a.setPid(Integer.parseInt(pid));
a.setAttname(attname);
a.setAttdis(attdis);
a.setRemark(remark);
a.setAttchnum(1);
a.setStarttime(new Date());
a.setUpdatetime(new Date());
//对文件进行处理 得到文件的名称
boolean flag=false;
try {
String filepath= System.currentTimeMillis()+multipartFile.getOriginalFilename();
//文件上传路径
String path="d:\\up";
//判断路径是否存在,不存在就创建
File file=new File(path);
if (!file.exists()){
file.mkdirs();
}
//将路径名和文件名称拼接,得到文件上传的绝对路径
File uploadfile=new File(path,filepath);
multipartFile.transferTo(uploadfile);
a.setPath(filepath);
flag=true;
} catch (IOException e) {
e.printStackTrace();
}
if (flag=true){
int num=attachmentService.addAccament(a);
if (num>0){
return "redirect:doindexAttachment";
}
}
return "redirect:goaddattachment";
}
2 文件下载
public ResponseEntity<byte[]> download(String filename){
try {
String path="d:\\up";
File file=new File(path,filename);
HttpHeaders header=new HttpHeaders();
header.setContentDispositionFormData("attchment",filename);
header.setContentType(MediaType.APPLICATION_OCTET_STREAM);
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),header, HttpStatus.OK);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
3 删除文件
@Override
public Integer deleteById(int[] nums) {
//删除图片
String path="d:\\up";
boolean flag=true;
Integer num=-1;
// 拿到数组 查询出所有的图片
if (nums!=null&&nums.length>0){
try {
for (int i=0;i<nums.length;i++){
Attachment attachment = attachmentMapper.selectById(nums[i]);
if (attachment.getPath()!=null&&attachment.getPath()!=""){
File file=new File(path,attachment.getPath());
if (file.exists()){
file.delete();
}
}
}
} catch (Exception e) {
flag=false;
e.printStackTrace();
}
//图片删除成功后删除数据
if (flag==true){
num = attachmentMapper.deleteById(nums);
}
}
return num;
}
备注
这是maven下的controller层 常用文件上传下载的固定代码
那些类是自己创建的,可更改 有关文件部分可直接复制