1.首先要導入文件上傳需要的jar包
commons-fileupload-1.3.2.jar 用於文件上傳,但是只有這個包也是不行的 , commons-fileupload-1.3.2.jar 依賴於 commons-io-2.5.jar 一起使用
2.在配置文件中配置文件解析器,默認是關閉的,所以要打開一下,在spring-mvc配置文件中配置一下
<!-- 文件解析器 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8"></property>
<!-- 指定所上傳的總大小不能超過200KB。注意maxUploadSize屬性的限制不是針對單個文件,而是所有文件 -->
<property name="maxUploadSize" value="200000"></property>
</bean>
3.controller 控制層寫調用的方法
<!-- 注解訪問層接口 並注入 用於最后調用方法--!>
@Resource
private StudentDao StudentDao;
public void setStudentDao(StudentDao studentDao) {
StudentDao = studentDao;
}
<!-- 用注解方式,value指定從頁面的提交地址,method指定是用表單的方式提交過來的 -->
@RequestMapping(value="/add",method=RequestMethod.POST)
<!-- Student student指參數,我這里用的是Student實體類 MultipartFile photo指文件上傳的參數,與頁面name指必須一致,HttpServletRequest request獲取請求參數,File不提供request提交 -->
public String postAdd(Student student,MultipartFile photo, HttpServletRequest request) throws Exception{
<!-- 保存文件到指定的路徑 這里獲取的是服務器的絕對路徑 --!>
String realPath = request.getServletContext().getRealPath("/img");
<!--獲取文件名字 --!>
String oldName = photo.getOriginalFilename();
<!--加上后綴 賦給一個新的變量 --!>
String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."));
<!--把文件放到項目的指定地方 --!>
File dest = new File(realPath+File.separator+newName );
photo.transferTo(dest);
<!-- 把路徑賦給實體類所對應的列 用於添加到數據庫中--!>
student.setImg(newName);
<!-- 調用添加方法 重定向到查詢頁面 --!>
StudentDao.add(student);
return "redirect:/student/list";
}
以上是我的做的一個小示例,希望能幫助到你們!