Servlet SpringMVC实现文件上传
Servlet
a、jar包 :Commons-fileUpload.jar Commons-io.jar
b、配置 在form表单里要配置一个属性 enctype = “multipart/form-data”
<form action="uploadServlet" method="post" enctype="multipart/form-data">
学号:<input type="text" name="sno"/> <br>
姓名:<input type="text" name="sname"/> <br>
上传文件:<input type="file" name="spicture"/> <br>
<input type="submit" value="提交">
</form>
c、实现:新建Servlet
//处理编码
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=UTF-8");
response.setCharacterEncoding("utf-8");
//
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
try {
if (isMultipart) { //判断前台form表单是否有multiparty 属性
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List<FileItem> items = upload.parseRequest(request);
Iterator<FileItem> iter = items.iterator();
while(iter.hasNext()){
FileItem item = iter.next();
String fieldName = item.getFieldName();
if(item.isFormField()) {
int sno = -1;
String sname = null;
if (fieldName.equals("sno")) {
sno = Integer.parseInt(item.getString("utf-8"));
} else if (fieldName.equals("sname")) {
sname = item.getString("utf-8");
} else {
System.out.println("其他字段....");
}
}else{
//上传 //获取文件名
String fileName = item.getName();
//获取文件内容 //定义上传文件路径
String path = "E:\upload";
File file = new File(path,fileName);
item.write(file);
System.out.println("文件上传成功"+fileName);
return;
}
}
}
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
SpringMVC 实现文件上传
和servlet基本一样,都是通过 commons-io.jar和 commons.fileUpload.jar springmvc可以简化代码
-
jar包 commons-io.jar和commons - FileUpload.jar
-
配置 实现一个接口 CommonsMultipartResolver
<!-- 配置CommonsMultipartReslover,用于实现文件上传 将其加入IOC容器
springioc容器在初始化的时候 会自动寻找一个 id="multipartResolver"的bean,并将其将加入IOC容器
-->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8"></property>
<!-- 上传单个文件最大值 单位是byte -->
<property name="maxUploadSize" value="102400000"></property>
</bean>
- index.jsp
<form action="handler/testUpload" method="post" enctype="multipart/form-data">
<input type="file" name="file">
描述<input type="text" name="desc" >
<input type="submit" value="提交">
</form>
- 服务端
@RequestMapping(value = "testUpload")
public String testUpload(@RequestParam("desc") String desc,@RequestParam("file") MultipartFile file) throws IOException {
System.out.println("文件描述信息:"+file);
InputStream input = file.getInputStream(); //IO
//上传什么名字保存什么名字
String fileName = file.getOriginalFilename();
OutputStream output = new FileOutputStream("d:\"+fileName);
byte[] bs = new byte[100];
int len = -1;
while( (len = input.read(bs))!=-1) {
output.write(bs, 0, len);
}
output.close();
input.close();
//将file上传到服务器中的某一个硬盘文件中
System.out.println("上传成功");
return "success";
}