**1.原始的servlet文件上传下载(往前翻)
2.Struts2框架的文件上传(往前翻)
3.spring-Mvc框架的文件上传**
作为最常用的mvc框架,它的上传你怎么能不会?
回顾:servelet如何文件上传?
页面:请求方式post,enctype:multipart/form-data—Servlet 3.0之前版本(commons-fileupload.jar,commons-io.jar)然后用API实现上传。
3.0版本,在servlet打一个@Multipart注解,doPost方法request.getPart来获取一个Part类型的对象,part.write将文件写入系统中。
Springmvc文件上传:
采用servlet3.0版本的技术实现,实现的步骤:
*1. 首先spring-mvc.xml中配置一个处理带有文件上传请求的解析器*
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form method="post" action="upload" enctype="multipart/form-data">
<input type="file" name="upload">
<input type="submit">
</form>
</body>
</html>
3.uploadController.java
package king.zyt.controller;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.servlet.http.Part;
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("/upload")
public String upload(String fileName,@RequestParam("upload")Part part){
try {
String fileinfo=part.getHeader("Content-Disposition");
int beginIndex=fileinfo.lastIndexOf("=")+2;
int endIndex=fileinfo.length()-1;
fileName=fileinfo.substring(beginIndex, endIndex);
part.write("d:/"+fileName);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "success";
}
@RequestMapping("/upload2")
public String upload2(String username,@RequestParam("upload")MultipartFile file){
try {
InputStream in=file.getInputStream();
OutputStream out=new FileOutputStream("d:/bb.txt");
byte[] b=new byte[in.available()];
in.read(b);
out.write(b);
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "success";
}
/**
请求头 根据它找到上传文件名
Content-Disposition: form-data; name="upload"; filename="servlet2.docx"
Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document
*/
}