网站首页 / 育儿 / 正文

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

时间:2022-04-13 21:40:49 浏览:3546次 作者:用户投稿 【我要投诉/侵权/举报 删除信息】

多条告白如次剧本只需引入一次

零、本篇重心

引见SpringBoot对文献上传的机动摆设。引见MultipartFile接口。引见SpringBoot+Thymeleaf文献上传demo的调整。引见对文献典型,文献名长度等确定本领。一、SpringBoot对文献处置关系机动摆设

机动摆设是SpringBoot为咱们供给的便当之一,开拓者不妨在不作任何摆设的情景下,运用SpringBoot供给的默许树立,如处置文献须要的MultipartResolver。

@Configuration(proxyBeanMethods = false)@ConditionalOnClass({ Servlet.class, StandardServletMultipartResolver.class, MultipartConfigElement.class })@ConditionalOnProperty(prefix = "spring.servlet.multipart", name = "enabled", matchIfMissing = true)@ConditionalOnWebApplication(type = Type.SERVLET)@EnableConfigurationProperties(MultipartProperties.class)public class MultipartAutoConfiguration {private final MultipartProperties multipartProperties;public MultipartAutoConfiguration(MultipartProperties multipartProperties) {this.multipartProperties = multipartProperties;}@Bean@ConditionalOnMissingBean({ MultipartConfigElement.class, CommonsMultipartResolver.class })public MultipartConfigElement multipartConfigElement() {return this.multipartProperties.createMultipartConfig();}@Bean(name = DispatcherServlet.MULTIPART_RESOLVER_BEAN_NAME)@ConditionalOnMissingBean(MultipartResolver.class)public StandardServletMultipartResolver multipartResolver() {StandardServletMultipartResolver multipartResolver = new StandardServletMultipartResolver();multipartResolver.setResolveLazily(this.multipartProperties.isResolveLazily());return multipartResolver;}}Spring3.1之后扶助StandardServletMultipartResolver,且默许运用StandardServletMultipartResolver,它的便宜在乎:运用Servlet所供给的功效扶助,不须要依附任何其余的名目。想要机动摆设奏效,须要摆设spring.servlet.multipart.enabled=true,固然这个摆设默许即是true。关系的摆设树立在MultipartProperties中,个中字段即是对应的属性树立,典范字段有:enabled:能否打开文献上传机动摆设,默许打开。location:上传文献的偶尔目次。maxFileSize:最大文献巨细,以字节为单元,默许为1M。maxRequestSize:所有乞求的最大含量,默许为10M。fileSizeThreshold:文献巨细到达该阈值,将写入偶尔目次,默许为0,即一切文献城市径直写入磁盘偶尔文献中。resolveLazily:能否惰性处置乞求,默许为false。咱们也不妨自设置处置的详细,须要实行MultipartResolver接口。二、处置上传文献MultipartFile接口

SpringBoot为咱们供给了MultipartFile宏大接口,让咱们不妨获得上传文献的精细消息,如原始文献名,实质典型之类,接口实质如次:

public interface MultipartFile extends InputStreamSource { String getName(); //获得参数名 @Nullable String getOriginalFilename();//原始的文献名 @Nullable String getContentType();//实质典型 boolean isEmpty(); long getSize(); //巨细 byte[] getBytes() throws IOException;// 获得字节数组 InputStream getInputStream() throws IOException;//以流办法举行读取 default Resource getResource() { return new MultipartFileResource(this); } // 将上传的文献写入文献体例 void transferTo(File var1) throws IOException, IllegalStateException;// 写入指定path default void transferTo(Path dest) throws IOException, IllegalStateException { FileCopyUtils.copy(this.getInputStream(), Files.newOutputStream(dest)); }}三、SpringBoot+Thymeleaf调整demo

1、编写遏制器

/** * 文献上传 * * @author Summerday */@Controllerpublic class FileUploadController { private static final String UPLOADED_FOLDER = System.getProperty("user.dir"); @GetMapping("/") public String index() { return "file"; } @PostMapping("/upload") public String singleFileUpload(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) throws IOException { if (file.isEmpty()) { redirectAttributes.addFlashAttribute("msg", "文献为空,请采用你的文献上传"); return "redirect:uploadStatus"; } saveFile(file); redirectAttributes.addFlashAttribute("msg", "上传文献" + file.getOriginalFilename() + "胜利"); redirectAttributes.addFlashAttribute("url", "/upload/" + file.getOriginalFilename()); return "redirect:uploadStatus"; } private void saveFile(MultipartFile file) throws IOException { Path path = Paths.get(UPLOADED_FOLDER + "/" + file.getOriginalFilename()); file.transferTo(path); } @GetMapping("/uploadStatus") public String uploadStatus() { return "uploadStatus"; }}2、编写页面file.html

<html xmlns:th="http://www.thymeleaf.org"> <!--suppress ALL--><html lang="en"> <head> <meta charset="UTF-8"> <title>文献上传界面</title> </head> <body> <div> <form method="POST" enctype="multipart/form-data" action="/upload"> <table> <tr><td><input type="file" name="file" /></td></tr> <tr><td></td><td><input type="submit" value="上传" /></td></tr> </table> </form> </div> </body></html>3、编写页面uploadStatus.html

<!--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="${url}" alt=""> </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"); @Override public 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

/** * 文献上传 * * @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); // 写入file file.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; } /** * 此处自定?%

版权声明:
本文内容由互联网用户自发贡献,该文观点仅代表作者本人,因此内容不代表本站观点、本站不对文章中的任何观点负责,内容版权归原作者所有、内容只用于提供信息阅读,无任何商业用途。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站(文章、内容、图片、音频、视频)有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至353049283@qq.com举报,一经查实,本站将立刻删除、维护您的正当权益。