springboot教程6——文件上传
程序员文章站
2022-06-03 13:21:47
...
-
Spring Boot 默认使用 springMVC 包装好的解析器进行上传
-
添加代码
index.ftl(当前模板引擎是freemarker)
<!DOCTYPE html>
<html>
<head lang="en">
<title>Spring Boot Demo - FreeMarker</title>
<link href="/css/index.css" rel="stylesheet" />
</head>
<body>
<center>
<img src="/images/logo.png" />
<h1 id="title">${title}</h1>
</center>
<form method="POST" enctype="multipart/form-data" action="/file/upload">
文件:<input type="file" name="roncooFile" />
<input type="submit" value="上传" />
</form>
</body>
</html>
FileController.java
package com.roncoo.education.controller;
import java.io.File;
import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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;
/**
* spring-boot-demo-12-1
*
*/
@Controller
@RequestMapping(value = "/file")
public class FileController {
private static final Logger logger = LoggerFactory.getLogger(FileController.class);
@RequestMapping(value = "upload")
@ResponseBody
public String upload(@RequestParam("roncooFile") MultipartFile file) {
if (file.isEmpty()) {
return "文件为空";
}
// 获取文件名
String fileName = file.getOriginalFilename();
logger.info("上传的文件名为:" + fileName);
// 获取文件的后缀名
String suffixName = fileName.substring(fileName.lastIndexOf("."));
logger.info("上传的后缀名为:" + suffixName);
// 文件上传路径
String filePath = "d:/roncoo/ttt/";
// 解决中文问题,liunx下中文路径,图片显示问题
// fileName = UUID.randomUUID() + suffixName;
File dest = new File(filePath + fileName);
// 检测是否存在目录
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
try {
file.transferTo(dest);
return "上传成功";
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "上传失败";
}
}
application.properties
#最大支持文件大小
spring.http.multipart.max-file-size=2Mb
#最大支持请求大小
spring.http.multipart.max-request-size=10Mb
上一篇: 用phpmyadmin更改mysql5.0登录密码
下一篇: 基本算法之递归算法