上传
package com.xpl.controller; import org.apache.commons.io.FileUtils; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.io.IOException; import java.util.UUID; @Controller public class Update { @RequestMapping("/update") public String update(MultipartFile file) throws IOException { // 获取上传文件的文件名 String fileName = file.getOriginalFilename(); // 截取文件后缀 String suffix = fileName.substring(fileName.lastIndexOf(".")); // 生成新的文件名 String newName = UUID.randomUUID().toString(); // 保存到固定地址 FileUtils.copyInputStreamToFile(file.getInputStream(),new File("E:/"+newName+suffix)); return "index"; } }
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.xpl</groupId> <artifactId>downFile</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.3.19.RELEASE</version> </dependency> <dependency> <groupId>org.kie.modules</groupId> <artifactId>org-apache-commons-fileupload</artifactId> <version>6.5.0.Final</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.2</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> </dependency> </dependencies> </project>
<bean class="org.springframework.web.multipart.commons.CommonsMultipartResolver" id="multipartResolver"/>
<form action="/update" enctype="multipart/form-data" method="post"> 选择上传文件:<input type="file" name="file"><br/> 上传:<input type="submit" value="上传"> </form>
<bean class="org.springframework.web.multipart.commons.CommonsMultipartResolver" id="multipartResolver"> <property name="maxUploadSize" value="50"/> </bean> <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver" id="exceptionResolver"> <property name="exceptionMappings"> <props> <prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">err/MaxSize</prop> </props> </property> </bean>