前言参考:快速开发第一个SpringBoot应用css
这篇文章会讲解如何使用SpringBoot完成一个文件上传的过程,而且附带一些SpringBoot开发中须要注意的地方html
首先咱们写一个文件上传的html页面:picUpload.html前端
<!DOCTYPE HTML>
<html>
<head>
<title>pictureUploading</title>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8 ">
</head>
<body>
<form enctype="multipart/form-data" method="post" action="/upload">
文件:<input type="file" name="fileUpload"/>
<input type="submit" value="上传"/>
</form>
</body>
</html>
注意form标签里的enctype属性必须指定为:multipart/form-data。java
下面咱们看看经过Quick Start获得的项目的初始目录结构:
spring
SpringBoot官方文档告诉咱们,statis这个目录里面应该存放一些静态文件,好比 css、js、image而且能够直接被外部访问到。而templates这个目录则存放一些静态页面,如jsp、html、ftl。而且template这个目录里的内容外部是访问不到的。按照规范,咱们将picUpload.html文件放到templates目录下。后端
如今经过:localhost:8080/index.html是访问不到该页面的。按照之前学习SpringMVC的经验,应该写一个controller,经过这个controller跳转到picUpload.html页面上去,再返回给用户。app
下面咱们新建一个controller,用作页面的跳转:dom
@Controller
public class ToHtmlController {
@RequestMapping("/picUpload")
public String picUpload(){
return "picUpload";
}
}
此时若是咱们启动项目,并访问localhost:8080/picUpload这个url,页面会报错以下:jsp
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Mon Jun 04 19:10:46 CST 2018
There was an unexpected error (type=Internal Server Error, status=500).
Circular view path [picUpload]: would dispatch back to the current handler URL [/picUpload] again. Check your ViewResolver setup! (Hint: This may be the result of an unspecified view, due to default view name generation.)spring-boot
注意最后一句提示,意思就是咱们没有指明模板引擎,这里咱们使用thymeleaf,在pom.xml文件中添加以下依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
而后启动项目,访问localhost:8080/picUpload,看到页面以下:
当选择完文件,点击上传按钮后,form表单会按照action属性值的url进行后端访问action="/upload"
,此时咱们应该写一个controller来接收前端传来的图片,并将图片放到项目的static目录下。
图片处理controller以下:
/** * 图片上传 * @author 吴洋 * */
@RestController
public class PicUploadController {
@PostMapping("/upload")
public Object upload(MultipartFile fileUpload){
//获取文件名
String fileName = fileUpload.getOriginalFilename();
//获取文件后缀名
String suffixName = fileName.substring(fileName.lastIndexOf("."));
//从新生成文件名
fileName = UUID.randomUUID()+suffixName;
//指定本地文件夹存储图片
String filePath = "D:/SpringBoot/demo/src/main/resources/static/";
try {
//将图片保存到static文件夹里
fileUpload.transferTo(new File(filePath+fileName));
return new Massage(0,"success to upload");
} catch (Exception e) {
e.printStackTrace();
return new Massage(-1,"fail to upload");
}
}
}
这里我新建了一个Message类,来向前端返回是否上传成功的信息。
public class Massage {
//0表示成功;-1表示失败
int status;
//向前端返回的内容
String massage;
public Massage() {
super();
}
public Massage(int status, String massage) {
super();
this.status = status;
this.massage = massage;
}
//get/set方法
}
此时咱们启动项目,并访问localhost:8080/picUpload,选择图片,点击上传。页面返回以下:
说明图片上传成功了,refresh项目,能够看到static目录下出现了咱们上传的图片,而且名称也随机改变了。