【发布时间】:2021-04-01 13:49:53
【问题描述】:
我正在使用 Spring boot MultipartFile 来允许用户上传他们的文件,并且我想将上传的文件保存在项目目录或我的磁盘“C:\upload”(或它在本地工作的任何地方)中。当我提交任何文件时,我会收到 403 错误禁止。 (spring-boot-starter-security 用于嵌入式登录)。
这是浏览器中打印的错误截图:403 Error
在控制台中我收到以下错误:
org.thymeleaf.exceptions.TemplateInputException: 解析模板时出错 [error],模板可能不存在或可能无法被任何已配置的模板解析器访问
这是我的项目结构:project structure
这是我的上传控制器:
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
@Controller
public class UploadController {
//Save the uploaded file to this folder
private static String UPLOADED_FOLDER = "./src/main/resources/uploaded";
@GetMapping("/test")
public String index() {
return "upload";
}
@PostMapping("/upload")
public String singleFileUpload(@RequestParam("file") MultipartFile file,
RedirectAttributes redirectAttributes) {
if (file.isEmpty()) {
redirectAttributes.addFlashAttribute("message", "Please select a file to upload");
return "redirect:uploadStatus";
}
try {
// Get the file and save it somewhere
byte[] bytes = file.getBytes();
Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename());
Files.write(path, bytes);
redirectAttributes.addFlashAttribute("message",
"You successfully uploaded '" + file.getOriginalFilename() + "'");
} catch (IOException e) {
e.printStackTrace();
}
return "redirect:/uploadStatus";
}
@GetMapping("/uploadStatus")
public String uploadStatus() {
return "uploadStatus";
}
}
这里是upload.html:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<body>
<h1>You can upload your files here</h1>
<form method="POST" action="/upload" enctype="multipart/form-data">
<input type="file" name="file" /><br/><br/>
<input type="submit" value="Submit" />
</form>
</body>
</html>
上传状态.html:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<body>
<h1>Upload Status</h1>
<div th:if="${message}">
<h2 th:text="${message}"/>
</div>
</body>
</html>
我使用thymeleaf作为模板引擎:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
我仍然是初学者,并且对 spring boot 有基本的经验,我一直在寻找解决方案,所以请任何帮助/建议来解决问题。
提前致谢!
【问题讨论】:
-
你能包含完整的堆栈跟踪吗?执行是否进入catch块?
-
这个回答你的问题stackoverflow.com/questions/32064000/… 吗?
-
检查一下,找出你身边的问题:en.wikipedia.org/wiki/HTTP_403
标签: java spring-boot spring-security thymeleaf