一、传统方式
1. 导入文件上传的jar包
<dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency>
2. 编写文件上传的jsp页面
<h3>文件上传</h3>
<form action="user/fileupload" method="post" enctype="multipart/form-data">
选择文件:<input type="file" name="upload"/><br/>
<input type="submit" value="上传文件"/>
</form>
3. 编写文件上传的Controller控制器(文件上传传统方式)
@Controller @RequestMapping("/user") public class UserController { /** * 文件上传 * @return */ @RequestMapping("/fileupload1") public String fileupload1(HttpServletRequest request) throws Exception { System.out.println("文件上传"); //使用fileupload组件完成文件上传 //上传的位置 String path = request.getSession().getServletContext().getRealPath("/uploads/"); //判断该路径是否存在 File file = new File(path); if (!file.exists()){ //创建该文件夹 file.mkdirs(); } // 解析request对象,获取上传文件项 DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); //解析request List<FileItem> items = upload.parseRequest(request); //遍历 for (FileItem item:items){ //进行判断,当前item对象是否是上传文件项 if (item.isFormField()){ //说明是一个普通表单向 }else{ //说明上传文件项 //获取上传文件的名称 String filename = item.getName(); //把文件的名称设置唯一值,uuid String uuid = UUID.randomUUID().toString().replace("-", ""); filename = uuid + filename; //完成文件上传 item.write(new File(path,filename)); //删除临时文件 item.delete(); } } return "success"; } }
二、springmvc方式
1、在springmvc.xml中配置文件解析器
<!--配置文件解析器-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!--配置文件上传大小-->
<property name="maxUploadSize" value="10485760" />
</bean>
2、springmvc上传文件
/** * springmvc方式上传 * @param request * @return * @throws Exception */ @RequestMapping("/fileupload2") public String fileupload2(HttpServletRequest request, MultipartFile upload) throws Exception { System.out.println("springmvc文件上传"); //使用fileupload组件完成文件上传 //上传的位置 String path = request.getSession().getServletContext().getRealPath("/uploads/"); //判断该路径是否存在 File file = new File(path); if (!file.exists()){ //创建该文件夹 file.mkdirs(); } //说明上传文件项 //获取上传文件的名称 String filename = upload.getOriginalFilename(); //把文件的名称设置唯一值,uuid String uuid = UUID.randomUUID().toString().replace("-", ""); filename = uuid + "_" + filename; //完成文件上传 upload.transferTo(new File(path,filename)); return "success"; }
三、springmvc跨服务器上传文件
1、搭建图片服务器
2、导入需要的jar包
<dependency> <groupId>com.sun.jersey</groupId> <artifactId>jersey-core</artifactId> <version>1.18.1</version> </dependency> <dependency> <groupId>com.sun.jersey</groupId> <artifactId>jersey-client</artifactId> <version>1.18.1</version> </dependency>
---恢复内容结束---