单个文件上传
- jsp页面
<body>
<form action="shangchuan.do" method="post" enctype="multipart/form-data">
文件<input type="file" name="fileName"> //name与方法参数保持一致
<input type="submit" value="上传">
</form>
</body>`
2.文件上传的视图解析器
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
</bean>
3.编写Controller
package com.controller;
import java.io.File;
import java.io.IOException;
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("shangchuan.do")
public String upload(@RequestParam(value="fileName")MultipartFile fileName,HttpServletRequest request) throws IllegalStateException, IOException{
//获取上传文件的 原始名称:123+时间戳.jpg
String fname=fileName.getOriginalFilename();
fname=System.currentTimeMillis()+fname;//时间戳
System.out.println("原始名:"+fname);
System.out.println("临时名:"+fileName.getName());
//获取服务器上的upload文件夹的物理位置 :e:\tomcat\...\...
String path=request.getSession().getServletContext().getRealPath("/upload");
System.out.println("upload文件夹位置:"+path);
File target=new File(path+"\\"+fname);
fileName.transferTo(target);保存文件到指定目录
return "success.jsp";
}
4.文件夹:服务器的文件夹
上传后的信息最终会放到服务器上的upload文件夹中
5.结果:
多个文件上传
- jsp页面
<body>
<form action="duoshangchuan.do" method="post" enctype="multipart/form-data">
<input type="file" name="files"> <br>
<input type="file" name="files"> <br>
<input type="file" name="files"> <br>
<input type="submit" value="都上传">
</form>
</body>`
2.文件上传的视图解析器
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
</bean>
3.编写Controller
package com.controller;
import java.io.File;
import java.io.IOException;
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("duoshangchuan.do")
public String duoshangchuan(@RequestParam(value="files")MultipartFile[] files,HttpServletRequest request) throws IllegalStateException, IOException{
if(files!=null&&files.length>0){
for(int i=0;i<files.length;i++){
MultipartFile file=files[i];
String fname=file.getOriginalFilename();
fname=System.currentTimeMillis()+fname;
String path=request.getSession().getServletContext().getRealPath("/upload");
System.out.println("路径:"+path+"名:"+fname);
File target=new File(path+"/"+fname);
file.transferTo(target);
}
}
return "success.jsp";
}
}
4.文件夹:服务器的文件夹
上传后的信息最终会放到服务器上的upload文件夹中
5.结果: