-
- <dependency>
- <groupId>commons-iogroupId>
- <artifactId>commons-ioartifactId>
- <version>2.4version>
- dependency>
- <dependency>
- <groupId>commons-fileuploadgroupId>
- <artifactId>commons-fileuploadartifactId>
- <version>1.4version>
- <exclusions>
- <exclusion>
- <artifactId>commons-ioartifactId>
- <groupId>commons-iogroupId>
- exclusion>
- exclusions>
- dependency>
- <dependency>
- <groupId>commons-codecgroupId>
- <artifactId>commons-codecartifactId>
- <version>1.13version>
- dependency>
-
- <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
-
- <property name="defaultEncoding" value="utf-8"/>
-
- <property name="maxUploadSize" value="10485760000"/>
-
- <property name="maxInMemorySize" value="40960"/>
- bean>
注意:文件上传的form表单必须加上enctype="multipart/form-data"
- <form action="${request.contextPath}/brand/add" method="post" enctype="multipart/form-data">
- Logo:<input type="file" name="logo">
- <input type="submit" value="提交">
- form>
注意:上传文件的Controller类必须加上@MultipartConfig注解,并且文件上传的接口必须时Post请求。
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.PostMapping;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RequestParam;
- import org.springframework.web.multipart.MultipartFile;
-
- import javax.servlet.annotation.MultipartConfig;
- import java.io.File;
- import java.io.IOException;
-
- /**
- * @author JngKang
- * @date 2022-05-16 09:27
- */
- @Controller
- @MultipartConfig
- @RequestMapping("brand")
- public class BrandController {
- @PostMapping("add")
- public void add(@RequestParam("logo") MultipartFile multipartFile) {
- try {
- multipartFile.transferTo(new File("d:/a.jpg"));
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
- }
后端优化
- import com.xxx.constant.WegoConst;
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.PostMapping;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RequestParam;
- import org.springframework.web.multipart.MultipartFile;
-
- import javax.servlet.annotation.MultipartConfig;
- import java.io.File;
- import java.io.IOException;
- import java.util.UUID;
-
- /**
- * @author JngKang
- * @date 2022-05-16 09:27
- */
- @Controller
- @MultipartConfig
- @RequestMapping("brand")
- public class BrandController {
- @PostMapping("add")
- public void add(@RequestParam("logo") MultipartFile multipartFile) {
- String fileName = multipartFile.getOriginalFilename();
- String suffix = fileName.substring(fileName.lastIndexOf("."));
- String filePath = WegoConst.FILEPATH + UUID.randomUUID() + suffix;
- try {
- multipartFile.transferTo(new File(filePath));
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
- }