spring上传到文件服务器 spring文件上传大小限制( 二 )


<!--suppress ALL--><html xmlns:th="http://www.thymeleaf.org"><html lang="en"><head><meta charset="UTF-8"><title>文献上传界面</title></head><body><div th:if="${msg}"><h2 th:text="${msg}"/></div><div ><img src="" th:src="https://www.juguize.com/b/${url}" ></div></body></html>4、编写摆设
server.port=8081spring.servlet.multipart.max-file-size=10MBspring.servlet.multipart.max-request-size=10MB5、摆设假造路途映照
这一步利害常要害的,咱们将文献上传到效劳器上时,咱们须要将咱们的乞求路途和效劳器上的路途举行对应,否则很有大概文献上传胜利,但考察波折:
@Configurationpublic class MvcConfig implements WebMvcConfigurer {private static final String UPLOADED_FOLDER = System.getProperty("user.dir");@Overridepublic void addResourceHandlers(ResourceHandlerRegistry registry) {registry.addResourceHandler("/upload/**").addResourceLocations("file:///" + UPLOADED_FOLDER + "/");}}对应联系须要本人去设置,即使考察波折,不妨试着打字与印刷以次路途,看看能否缺点和失误了路途分割符 。
提防:即使addResourceHandler不要写成处置/**,如许会阻挡掉其余的乞求
6、尝试页面
实行mvn spring-boot:run,启用步调,考察http://localhost:8081/,采用文献,点击上传按钮,咱们的名目目次下展示了mongo.jpg,而且页面也胜利表露:
四、SpringBoot的Restful作风,归来url
【spring上传到文件服务器spring文件上传大小限制】/** * 文献上传 * * @author Summerday */@RestControllerpublic class FileUploadRestController {/*** 文献名长度*/private static final int DEFAULT_FILE_NAME_LENGTH = 100;/*** 承诺的文献典型*/private static final String[] ALLOWED_EXTENSIONS = {"jpg", "img", "png", "gif"};/*** 名目路途*/private static final String UPLOADED_FOLDER = System.getProperty("user.dir");@PostMapping("/restUpload")public Map<String,Object> singleFileUpload(@RequestParam("file") MultipartFile file) throws Exception {if (file.isEmpty()) {throw new Exception("文献为空!");}String filename = upload(file);String url = "/upload/" + filename;Map<String,Object> map = new HashMap<>(2);map.put("msg","上传胜利");map.put("url",url);return map;}/*** 上传本领*/private String upload(MultipartFile file) throws Exception {int len = file.getOriginalFilename().length();if (len > DEFAULT_FILE_NAME_LENGTH) {throw new Exception("文献名胜过控制!");}String extension = getExtension(file);if(!isValidExtension(extension)){throw new Exception("文献 *** 不精确");}// 自设置文献名String filename = getPathName(file);// 获得file东西File desc = getFile(filename);// 写入filefile.transferTo(desc);return filename;}/*** 获得file东西*/private File getFile(String filename) throws IOException {File file = new File(UPLOADED_FOLDER + "/" + filename);if(!file.getParentFile().exists()){file.getParentFile().mkdirs();}if(!file.exists()){file.createNewFile();}return file;}/*** 考证文献典型能否精确*/private boolean isValidExtension(String extension) {for (String allowedExtension : ALLOWED_EXTENSIONS) {if(extension.equalsIgnoreCase(allowedExtension)){return true;}}return false;}/*** 此处自定?%

推荐阅读