首先要导包,用的的包是:
commons-fileupload-*.*.*.jar
commons-io-*.*.jar
*号代表版本号
这里给大家分享一下下载链接:https://files.cnblogs.com/files/chuanyueinlife/SpringMVC%E4%B8%8A%E4%BC%A0jar%E5%8C%85.zip
jsp页面:
<form action="upload.do" method="post" enctype="multipart/form-data"> 选择文件:<input type="file" name="file">
<br>
<input type="submit" value="提交"> </form>
Controller:
package controller; import java.io.File; import java.io.IOException; import java.util.UUID; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; @Controller public class UploadController { @RequestMapping("upload.do") public String upload(HttpServletRequest request, String userName, @RequestParam(value = "file") MultipartFile file) throws IllegalStateException, IOException { String upload_path = request.getSession().getServletContext().getRealPath("upload"); String file_name = file.getOriginalFilename(); file_name = file_name.substring(file_name.lastIndexOf("\\") + 1); String final_pathname = upload_path + "\\" + UUID.randomUUID() + "-" + file_name; File f = new File(final_pathname); file.transferTo(f); return "forward:index.jsp"; } }
Springmvc.xml文件配置:
<!-- 文件上传配置 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize"> <value>10240000</value> </property> </bean>