2021SC@SDUS
FileController 上传下载类
package com.cs.cp.common;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.WebUtils;
import com.alibaba.fastjson.JSONObject;
@Controller
public class FileController {
/**
* 文件上传功能
*
* @param file
* @return
* @throws IOException
*/
@RequestMapping(value = "/fileUpload", produces = "text/plain;charset=utf-8", method = RequestMethod.POST)
@ResponseBody
public String upload(MultipartFile file, HttpServletRequest request, Exception ex) throws IOException {
ResponseVo resVo = new ResponseVo();
resVo.setCmd("uploadFile");
if (file.getOriginalFilename() == "") {// 文件为空不上传
resVo.setResult(1);
resVo.setStatu(1);
resVo.setResultNote("no select file upload");
return JSONObject.toJSON(resVo).toString();
}
// 判断文件名有没有.
if (file.getOriginalFilename().indexOf(".") == -1) {
// 文件格式不确定,无法上传
resVo.setResult(1);
resVo.setStatu(1);
resVo.setResultNote("File format cannot be parsed");
return JSONObject.toJSON(resVo).toString();
}
// 文件上传的大小限制 5MB
if (file.getSize() > 5242880) {
resVo.setResult(1);
resVo.setStatu(1);
resVo.setResultNote("file is too big and greater than 5MB");
return JSONObject.toJSON(resVo).toString();
}
Date currentTime = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
String dateString = formatter.format(currentTime);
String path = request.getSession().getServletContext().getRealPath("upload/" + dateString);
String fileName = file.getOriginalFilename();
// 获取后缀
String[] arr = fileName.split("\\.");
String newFileName = new Date().getTime() + "." + arr[arr.length - 1];
System.out.println(newFileName);
File dir = new File(path, newFileName);
if (!dir.exists()) {
dir.mkdirs();
}
// MultipartFile自带的解析方法
file.transferTo(dir);
resVo.setDetail("/" + dateString + newFileName);
return JSONObject.toJSON(resVo).toString();
}
/**
* 文件下载功能
*
* @param request
* @param response
* @throws Exception
*/
@RequestMapping("/fileDown")
public void down(HttpServletRequest request, HttpServletResponse response) throws Exception {
ResponseVo resVo = new ResponseVo();
String name = request.getParameter("name").trim();
String[] temp = name.split("/");/// 1525415098397.txt
// 模拟文件,myfile.txt为需要下载的文件
String fileName = request.getSession().getServletContext().getRealPath("upload") + name;
// 判断文件是否存
File file = new File(request.getSession().getServletContext().getRealPath("upload") + name);
if (!file.exists()) {//文件不存在
return;
}
// 获取输入流
InputStream bis = new BufferedInputStream(new FileInputStream(new File(fileName)));
// 假如以中文名下载的话
// String filename = "下载文件.txt";
String filename = temp[temp.length - 1];
// 转码,免得文件名中文乱码
filename = URLEncoder.encode(filename, "UTF-8");
// 设置文件下载头
response.addHeader("Content-Disposition", "attachment;filename=" + filename);
// 1.设置文件ContentType类型,这样设置,会自动判断下载文件类型
response.setContentType("multipart/form-data");
BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
int len = 0;
while ((len = bis.read()) != -1) {
out.write(len);
out.flush();
}
out.close();
}
package com.deepincoding.fileuploadformpage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.FileSystemUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder;
import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.List;
import java.util.stream.Collectors;
@Controller
public class FileController {
//上传文件路径
@Value("${file.base.director}")
private String fileBaseDirector;
private Path fileBasePath;
@Autowired
private void createDirectories(){
try {
Files.createDirectories(Paths.get(fileBaseDirector));
} catch (IOException e) {
e.printStackTrace();
}
this.fileBasePath = Path.of(fileBaseDirector);
}
@GetMapping("/")
public String index(){
return "index";
}
@GetMapping("/upload")
public String upload(){
return "upload";
}
@GetMapping("/files")
public String files(Model model) throws IOException {
List<FileObject> filesAll = Files.walk(fileBasePath,1)
.filter(path -> !path.equals(fileBasePath))
.map(path -> {
String url = MvcUriComponentsBuilder.fromMethodName(FileController.class,"loadFile",path.getFileName().toString()).build().toString();
FileObject fileObject = new FileObject(path.getFileName().toString(),url);
return fileObject;
}).collect(Collectors.toList());
model.addAttribute("files",filesAll);
return "files";
}
@GetMapping("/delete/{fileName}")
public String deleteFile(@PathVariable String fileName){
Path deletePath = fileBasePath.resolve(fileName);
Boolean isDelete = Boolean.FALSE;
try {
isDelete = FileSystemUtils.deleteRecursively(deletePath);
} catch (IOException e) {
e.printStackTrace();
}
return "redirect:/files";
}
@PostMapping("/upload")
public String upload(@RequestParam("file") MultipartFile file){
String fileName = StringUtils.cleanPath(file.getOriginalFilename());
Path path = Path.of(fileBaseDirector + fileName);
try {
Files.copy(file.getInputStream(),path,StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
e.printStackTrace();
}
return "redirect:/files";
}
}