本文主要是介绍Jojo的作业系统,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
简单的文件上传
代码如下
@RestController
@RequestMapping("/file")
public class FileController {@RequestMapping(method = RequestMethod.POST, value ="/upload")@ResponseBodypublic String uploadFile(@RequestParam("fileName") MultipartFile file) throws IOException {System.out.println("file name = "+file.getOriginalFilename());if (file.isEmpty()) {return "file is empty";}// 获取文件名String fileName = file.getOriginalFilename();// 获取后缀String suffixName = fileName.substring(fileName.lastIndexOf("."));// 文件上产的路径String filePath = "d:\\macro";// fileName处理
// fileName = filePath+ UUID.randomUUID()+fileName;fileName = filePath+ Path.SEPARATOR+fileName;// 文件对象File dest = new File(fileName);// 创建路径if(!dest.getParentFile().exists()){dest.getParentFile().mkdir();}try {file.transferTo(dest);return "上传成功";} catch (IOException e) {e.printStackTrace();throw e;}}@RequestMapping("download")public void download(HttpServletResponse response) throws FileNotFoundException {File file =new File("C:\\Users\\ASUS\\Desktop\\spring-boot-reference.pdf");FileInputStream fileInputStream=new FileInputStream(file);// 设置被下载而不是被打开response.setContentType("application/gorce-download");// 设置被第三方工具打开,设置下载的文件名response.addHeader("Content-disposition","attachment;fileName=spring-boot-reference.pdf");try {OutputStream outputStream = response.getOutputStream();byte[] bytes = new byte[1024];int len = 0;while ((len = fileInputStream.read(bytes))!=-1){outputStream.write(bytes,0,len);}} catch (IOException e) {e.printStackTrace();}}
}
Postman的设置,注意不要添加任何header
引入注册登录系统
这篇关于Jojo的作业系统的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!