文件上传
前言:本篇博客只讲述了单文件的上传,如有不对的地方还请指出
jsp
<form action="upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" placeholder="" required />
<input type="submit" value="提交">
</from>
文件上传
1. 过程描述
- 拿到MultipartFile的对象
- 根据MultipartFile的对象获取源文件的名称
- 在服务机创建文件,文件类型需要和源文件类型保持一致
- 通过流把临时文件内容传入创建的服务机文件
2. 代码(Controller)
@RequestMapping(value = "upload",method = RequestMethod.POST)
public String upload(Model m,
@RequestParam(value = "fileName") String fileName,
@RequestParam(value = "groupName") String groupName,
@RequestParam(value = "owner") String owner,
@RequestParam(value = "fileMessage") String fileMessage,
@RequestParam(value = "file") MultipartFile file){
// 判断文件是否为空
if(file.isEmpty()){
m.addAttribute("infor","文件为空");
return "upload";
}
// 获取源文件名称
String fileRealName = file.getOriginalFilename();
// 获取源文件大小
int size = (int) file.getSize();
System.out.println(fileRealName + "-->" + size);
// 定义文件的存储路径
String path = "E:/file" + "/" + fileRealName;
// 新建本地文件
File dest = new File(path);
if(!dest.getParentFile().exists()){ //判断文件父目录是否存在
// 创建父目录
dest.getParentFile().mkdir();
}
// 定义时间格式
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String infor = "";
try {
// 资源信息存数据库
recourcesMapper.save(fileName,groupName,owner,fileMessage,path,df.format(new Date()),0);
file.transferTo(dest); //保存文件
infor = "资源上传成功";
} catch (IllegalStateException | IOException e) {
e.printStackTrace();
infor = "资源上传失败";
}
if(infor.equals("资源上传成功")){
return "redirect:/listPage";
}
m.addAttribute("infor",infor);
return "upload";
}
文件下载
1. 过程描述
- 根据实际文件路径创建文件对象(为了后面的io操作)
- 设置响应头与相应内容类型
- 根据相应对象获取输出流
- 用io读取文件内容并写入相应对象的输出流
2. 代码(Controller)
public String downLoad(HttpServletResponse response,
@RequestParam(value = "id") Integer id){
// 从数据库读取文件路径
String path = recourcesMapper.findResourcePath(id);
// 切割字符串
String[] str = path.split("/");
// 获取文件名包括拓展名
String filename = str[str.length-1];
// 根据实际的文件创建文件对象
File file = new File(path);
//判断文件父目录是否存在
if(file.exists()){
// 设置内容的类型
response.setContentType("application/force-download");
// 设置响应头
response.setHeader("Content-Disposition", "attachment;fileName=" + filename);
byte[] buffer = new byte[1024];
//文件输入流
FileInputStream fis = null;
// 输入流缓存
BufferedInputStream bis = null;
// 输出流
OutputStream os = null;
try {
// 获取响应对象的输出流
os = response.getOutputStream();
// 文件输入流
fis = new FileInputStream(file);
// 缓存输入流
bis = new BufferedInputStream(fis);
// 数组从输入流缓存读取数据,返回数据是读取的byte个数
int i = bis.read(buffer);
while(i != -1){
// 数据写到输出流
os.write(buffer);
// 数组从输入流缓存读取数据
i = bis.read(buffer);
}
} catch (Exception e) {
e.printStackTrace();
}
try {
assert bis != null;
// 关闭缓存流
bis.close();
// 关闭文件流
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
两个示例代码都包含了实际业务