小贴士,eclipse中复制一份已有的项目
1.copy,改名
2.右键---properties----web Project Settings—更改访问路径Context root写入新的文件名
一、单个文件上传
1)jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> <% pageContext.setAttribute("ctp", request.getContextPath()); %> </head> <body> <!-- 文件上传 1.写表单;:enctype="multipart/form-data" 2.导入fileuplod包 commons-fileupload-1.2.1.jar commons-io-2.0.jar 3.javaweb....... 3.现在用框架 只需要在springmvc配置文件中,编写一个文件上传解析器MultiPartResolver九大组件之一 4.文件上传请求处理写Controller --> <!-- action最好写全路径 --> ${msg } <!-- 取一下model保存的提示信息 --> <form action="${ctp }/upload" method="post" enctype="multipart/form-data"> 用户头像:<input type="file" name="headerimg"/><br/> 用户名:<input type="text" name="username"/><br/> <input type="submit"/> </form> </body> </html>
2)springmvc.xml
编写一个文件上传解析器MultiPartResolver九大组件之一,其余配置都是标配
<context:component-scan base-package="com.atguigu"></context:component-scan> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/pages/"></property> <property name="suffix" value=".jsp"></property> </bean> <!-- 配置文件上传解析器MultiPartResolver接口,用CommonsMultipartResolver实现类 id必须是multipartResolver --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="#{1024*1024*20}"></property> <property name="defaultEncoding" value="UTF-8"></property> </bean> <mvc:default-servlet-handler/> <mvc:annotation-driven ></mvc:annotation-driven>
3)Controller
@Controller public class FileUploadController { @RequestMapping("/upload") public String upload(@RequestParam(value="username",required = false)String username, @RequestParam("headerimg")MultipartFile file, Model model) { System.out.println("上传文件的信息"); System.out.println("文件的名字:"+file.getName());//假名(jsp文件项的<name=“”>) System.out.println("文件的名字:"+file.getOriginalFilename());//真名 //文件保存 try { file.transferTo(new File("G:\\"+file.getOriginalFilename())); model.addAttribute("msg","文件上传成功了"); } catch (Exception e) { // TODO Auto-generated catch block model.addAttribute("msg","文件上传失败了"+e.getMessage()); } //懒得再写新的jsp了 return "forward:/index.jsp"; } }
二、多个文件上传
1)jsp里多写几个<input type="file" name="headerimg"/><br/>
2)Controller
@Controller public class FileUploadController { @RequestMapping("/upload") public String upload(@RequestParam(value="username",required = false)String username, @RequestParam("headerimg")MultipartFile[] file, Model model) { 对MultipartFile[] file增强型for循环 同上 //懒得再写新的jsp了 return "forward:/index.jsp"; } }