在TCP/IP中最早出现文件上传机制的是FTP。它是将文件由客户端发送到服务器的标准机制。但是在JSP编程中不能使用FTP方法上传文件,这是由于jsp运行机制所决定的。
文件的上传:通过为表单元素设置Method=”post” enctype=”multipart/form-data”,让表单提交的数据以二进制编码的方式提交。在接收此请求的Servlet中用二进制流来获取内容,就可以取得上传文件的内容。
表单的Enctype属性:
form的enctype属性:客户端浏览器对form的编码措施。
默认是对表单数据以 “application/x-www-form-urlencoded” 进行编码。这意味着在发送前对所有字符进行编码(把 “+” 转换为空格,把特殊字符转换为 ASCII 十六进制值)。
application/x-www-form-urlencoded 在发送前对所有字符进行编码(默认)。
multipart/form-data 不对字符编码。当使用有文件上传控件的表单时,该值是必需的。
text/plain 将空格转换为 “+” 符号,但不编码特殊字符。
文件下载原理:
需要通过HttpServletResponse的setContentType方法 设置ContentType头字段的值,这样设置之后浏览器才会以下载的方式来响应。通过HttpServletResponse 方法setHeader设置Content-Disposition头的值为”attachment;filename=\”” + filename。
使用IO流来读取文件内容。
利用Servlet实现文件的下载
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//获取文件下载路径
String path = getServletContext().getRealPath("/") + "images/";
String filename = req.getParameter("filename");
File file = new File(path + filename);
if(file.exists()){
//设置相应类型application/octet-stream
resp.setContentType("application/x-msdownload");
//设置头信息
resp.setHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");
InputStream inputStream = new FileInputStream(file);
ServletOutputStream ouputStream = resp.getOutputStream();
byte b[] = new byte[1024];
int n ;
while((n = inputStream.read(b)) != -1){
ouputStream.write(b,0,n);
}
//关闭流、释放资源
ouputStream.close();
inputStream.close();
}else{
req.setAttribute("errorResult", "文件不存在下载失败!");
RequestDispatcher dispatcher = req.getRequestDispatcher("jsp/01.jsp");
dispatcher.forward(req, resp);
}
}
利用Servlet获取上传的文件
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req,resp);
}
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//从request当中获取流信息
InputStream fileSource = req.getInputStream();
String tempFileName = "E:/tempFile";
//tempFile指向临时文件
File tempFile = new File(tempFileName);
//outputStram文件输出流指向这个临时文件
FileOutputStream outputStream = new FileOutputStream(tempFile);
byte b[] = new byte[1024];
int n;
while(( n = fileSource.read(b)) != -1){
outputStream.write(b, 0, n);
}
//关闭输出流、输入流
outputStream.close();
fileSource.close();
//获取上传文件的名称
RandomAccessFile randomFile = new RandomAccessFile(tempFile,"r");
randomFile.readLine();
String str = randomFile.readLine();
int beginIndex = str.lastIndexOf("\\") + 1;
int endIndex = str.lastIndexOf("\"");
String filename = str.substring(beginIndex, endIndex);
System.out.println("filename:" + filename);
//重新定位文件指针到文件头
randomFile.seek(0);
long startPosition = 0;
int i = 1;
//获取文件内容 开始位置
while(( n = randomFile.readByte()) != -1 && i <=4){
if(n == '\n'){
startPosition = randomFile.getFilePointer();
i ++;
}
}
startPosition = randomFile.getFilePointer() -1;
//获取文件内容 结束位置
randomFile.seek(randomFile.length());
long endPosition = randomFile.getFilePointer();
int j = 1;
while(endPosition >=0 && j<=2){
endPosition--;
randomFile.seek(endPosition);
if(randomFile.readByte() == '\n'){
j++;
}
}
endPosition = endPosition -1;
//设置保存上传文件的路径
String realPath = getServletContext().getRealPath("/") + "images";
File fileupload = new File(realPath);
if(!fileupload.exists()){
fileupload.mkdir();
}
File saveFile = new File(realPath,filename);
RandomAccessFile randomAccessFile = new RandomAccessFile(saveFile,"rw");
//从临时文件当中读取文件内容(根据起止位置获取)
randomFile.seek(startPosition);
while(startPosition < endPosition){
randomAccessFile.write(randomFile.readByte());
startPosition = randomFile.getFilePointer();
}
//关闭输入输出流、删除临时文件
randomAccessFile.close();
randomFile.close();
tempFile.delete();
req.setAttribute("result", "上传成功!");
RequestDispatcher dispatcher = req.getRequestDispatcher("jsp/01.jsp");
dispatcher.forward(req, resp);
}