工程目录结构
完整代码:
1、pom.xml
首先当然是添加依赖,用到thymeleaf模板渲染html页面
4.0.0 com.hello HelloBoot 0.0.1-SNAPSHOT jar UTF-8 org.springframework.boot spring-boot-starter-parent 2.0.1.BUILD-SNAPSHOT org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-thymeleaf spring-snapshots Spring Snapshots https://repo.spring.io/libs-snapshot true
如果遇到<parent>标签报错,看看和上面写的有出入吗---
2、application.properties
只有一行,关闭thymeleaf缓存
spring.thymeleaf.cache=false
3、file.html 页面
下载Insert title here 文件上传
4、HelloController.java 控制类
package com.hello;import java.io.BufferedInputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.io.OutputStream;import javax.servlet.http.HttpServletResponse;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.ResponseBody;import org.springframework.web.multipart.MultipartFile;@Controllerpublic class HelloController { //映射视图 @RequestMapping("/file") public String file() { return "/file"; } //上传 @RequestMapping("fileUpload") @ResponseBody public String fileUpload(@RequestParam("filename") MultipartFile file) { if(file.isEmpty()) { return "false"; } //将里面内容移动到目标文本文档 File dest = new File("D:/test.txt"); try { file.transferTo(dest); } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return "success"; } //下载 @RequestMapping("fileDownload") @ResponseBody public String fileDownload(HttpServletResponse res) { String fileName = "1.jpg"; res.setHeader("content-type", "application/octet-stream"); res.setContentType("application/octet-stream"); res.setHeader("Content-Disposition", "attachment;filename=" + fileName); byte[] buff = new byte[1024]; BufferedInputStream bis = null; OutputStream os = null; try { os = res.getOutputStream(); //获取zhi'ding bis = new BufferedInputStream( new FileInputStream(new File("D:/1.jpg"))); int i = bis.read(buff); while(i != -1) { //每次读取1024字节,就flush输出 os.write(buff, 0, buff.length); os.flush(); //然后继续读取下一个1024字节 i = bis.read(buff); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (bis != null) { try { bis.close(); } catch (IOException e) { e.printStackTrace(); } } } return "success"; } }
(1)file()方法return返回的是视图“file.html”,使用@Controller修饰类即可
(2)上传业务方法fileUpload(),return返回的是个字符串——“false“或”success”,不是html视图页面,所以不用渲染视图,
这里使用@Controller修饰类 和 @ResponseBody修饰方法
5、启动类App.java
package com.hello;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplicationpublic class App { public static void main(String[] args) { SpringApplication.run(App.class, args); }}