使用Servlet获取上传文件的输入流然后再解析里面的请求参数。
一、 Jsp页面
post方式提交,enctype为”multipart/form-data”。
<body>
<form action="uploadServlet.do" method="post" enctype="multipart/form-data">
<input type="file" id="myfile" name="myfile">
<input type="submit" value="提交">
<br>
${result}
<br>
下载:<a href="downloadServlet.do?filename=file.txt">file.txt</a>
<br>
${errorResult}
</form>
</body>
二、 创建文件上传Servlet
上传的文件无法直接保存,需创建一个临时文件,获取上传文件输入流信息,将文件输出流指向临时文件。从临时文件获取上传文件名、文件内容开始与结束指针,设置文件上传的路径,临时文件将文件内容输出到保存文件。
package com.yf.servlet;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class UploadServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("已接收到请求 ");
//从request当中获取流信息
InputStream fileSource = request.getInputStream();
String tempFileName = "E:/tempFile";
//tempFile指向临时文件
File tempFile = new File(tempFileName);
//outputStream文件输出流指向这个临时文件
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 benginIndex = str.lastIndexOf("=")+2;
int endIndex = str.lastIndexOf("\"");
String fileName = str.substring(benginIndex,endIndex);
System.out.println("文件名"+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 -=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 -= 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();
request.setAttribute("result", "上传成功");
RequestDispatcher dispatcher = request.getRequestDispatcher("index.jsp");
dispatcher.forward(request, response);
}
}
三、创建 文件下载Servlet
package com.yf.servlet;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class DownloadServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//获取文件下载路径
String path = getServletContext().getRealPath("/")+"images/";
String filename = request.getParameter("filename");
File file = new File(path+filename);
if(file.exists()){
//设置相应类型application/octet-stream
response.setContentType("application/x-msdownload");
//设置头信息
response.setHeader("Content-Disposition", "attachment;filename=\""+filename+"\"");
//读取文件
InputStream inputStream = new FileInputStream(file);
ServletOutputStream outputStream = response.getOutputStream();
byte b[] = new byte[1024];
int n;
while((n = inputStream.read(b))!=-1){
outputStream.write(b,0,n);
}
//关闭流
outputStream.close();
inputStream.close();
}else{
request.setAttribute("errorResult", "文件不存在下载失败");
request.getRequestDispatcher("index.jsp").forward(request, response);
}
}
}
四、 运行结果
选择上传文件:
点击提交
在tomcat下保存文件,页面显示上传成功。
点击下载,如果文件存在,则下载。不存在显示下载失败。