一、单文件上传
1. 导入新增的jar包
commons-fileupload-1.3.1.jar
commons-io-2.4.jar
2. 配置spring mvc文件上传解析器
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="1048576000"></property>
<property name="defaultEncoding" value="utf-8"></property>
</bean>
3. Jsp界面
<form action="upload.do" method="post" enctype="multipart/form-data">
file:<input type="file" name="file"/>
<input type="submit" value="上传"/>
</form>
4. Controller控制器处理类
@RequestMapping("/upload")
public String upload(@RequestParam("file") CommonsMultipartFile file,HttpServletRequest req) throws IOException {
// 获取upload文件的路径
String path = req.getRealPath("upload");
InputStream is = file.getInputStream();
OutputStream os = new FileOutputStream(new File(path,file.getOriginalFilename()));
int len = 0;
byte[] buffer = new byte[400];
// is.read(buffer)读取文件写入buffer数组字节 ,约定读
//取文件结束为-1,首先赋值给len(要看具体环境
// 一般约定-1为读结束,-2为都出错,此处也可设置为<0)
while((len=is.read(buffer))!=-1) {
// 文件未结束
// 指定从指定的字节数开始到输出流关闭写入len长度字节
// os.write(byte,off(数据偏移开始量),len(写入的字节数));
os.write(buffer, 0, len);
}
os.close();
is.close();
return "index.jsp";
}
5. 测试
输入请求url,并上传文件:
在tomcat里找到响应的项目
在upload中可以看到此文件
二、文件批量上传
与上文1、2点相同;
3.jsp界面
<form action="batch.do" method="post" enctype="multipart/form-data">
file:<br>
<input type="file" name="file"/><br><br>
<input type="file" name="file"/><br><br>
<input type="file" name="file"/><br><br>
<input type="file" name="file"/><br><br>
<input type="submit" value="上传"/>
</form>
4.控制器处理类
@RequestMapping("/batch")
public String upload(@RequestParam("file") CommonsMultipartFile file[],HttpServletRequest req) throws IOException {
System.out.println("start");
// 获取upload文件的路径
String path = req.getRealPath("upload");
for (int i = 0; i < file.length; i++) {
InputStream is = file[i].getInputStream();
OutputStream os = new FileOutputStream(new File(path,file[i].getOriginalFilename()));
int len = 0;
byte[] buffer = new byte[400];
// is.read(buffer)读取文件写入buffer数组字节 ,约定读取文件结束为-1,首先赋值给len(要看具体环境
// 一般约定-1为读结束,-2为都出错,此处也可设置为<0)
while((len=is.read(buffer))!=-1) {
// 文件未结束
// 指定从指定的字节数开始到输出流关闭写入len长度字节
// os.write(byte,off(数据偏移开始量),len(写入的字节数));
os.write(buffer, 0, len);
}
os.close();
is.close();
}
return "batch.jsp";