首先:在控制层 controller
建 FileUploadController
代码:
package com.example.springdemo.controller;
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;
import java.io.*;
@Controller
public class FileUploadController {
// 访问路径为:http://127.0.0.1:8080/file
@RequestMapping("/files")
public String file() {
return "/file";
}
/**
* 文件上传具体实现方法;
*
* @param file
* @return
*/
@RequestMapping("/upload")
@ResponseBody
public String handleFileUpload(@RequestParam("file") MultipartFile file) {
if (!file.isEmpty()) {
try {
/*
* 这段代码执行完毕之后,图片上传到了工程的跟路径; 大家自己扩散下思维,如果我们想把图片上传到
* d:/files大家是否能实现呢? 等等;
* 这里只是简单一个例子,请自行参考,融入到实际中可能需要大家自己做一些思考,比如: 1、文件路径; 2、文件名;
* 3、文件格式; 4、文件大小的限制;
*/
BufferedOutputStream out = new BufferedOutputStream(
new FileOutputStream(new File(
file.getOriginalFilename())));
out.write(file.getBytes());
out.flush();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
return "上传失败," + e.getMessage();
} catch (IOException e) {
e.printStackTrace();
return "上传失败," + e.getMessage();
}
return "上传成功";
} else return "上传失败,因为文件是空的.";
}
// 访问路径为:http://127.0.0.1:8080/file
@RequestMapping("/mutifile")
public String mutifile() {
return "/mutifile";
}
}
第二:在templates 建立一个 HTML文件
代码:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>Hello World!</title>
</head>
<body>
<form method="POST" enctype="multipart/form-data" action="/upload">
<p>
文件:<input type="file" name="file" />
</p>
<p>
<input type="submit" value="上传" />
</p>
</form>
</body>
</html>
3 直接启动项目即可 SpringdemoApplication
package com.example.springdemo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringdemoApplication {
public static void main(String[] args) {
SpringApplication.run(SpringdemoApplication.class, args);
}
}
浏览器:http://127.0.0.1:8080/files
快捷键:Alt+enter