一、文件上传
1.jsp页面中通过form表单上传文件
<form action="upload.do" method="post" enctype="multipart/form-data">
<input type="file" name="ff">
<input type="submit" value="上传">
</form>
//form表单enctype属性一定要改成multipart/form-data,这样才知道submit的是文件
2.创建UploadServlet
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setCharacterEncoding("utf-8");
request.setCharacterEncoding("utf-8");
response.setContentType("text/html");
//获得磁盘文件条目工厂
DiskFileItemFactory factory=new DiskFileItemFactory();
//通过调用jar包api,进行文件上传处理
ServletFileUpload upload=new ServletFileUpload(factory);
//单个文件最大10M
upload.setFileSizeMax(1024*1024*10);
//整个request请求的大小,一般比单个文件大小要大,因为包含request的其他请求信息
upload.setSizeMax(1024*1024*11);
try {
//解析request请求
List<FileItem> items=upload.parseRequest(request);
for(FileItem item:items){
//如果不是表单域,则为文件域,开始进行处理
if(!item.isFormField()){
//获取上传文件的名称
String fileName=item.getName();
//根据上传文件的名称,创建对应的文件
String path=request.getRealPath("/upload");
File f=new File(path+"/"+UUID.randomUUID()+"-"+fileName);
//写文件,实现上传功能
item.write(f);
}
}
} catch (Exception e) {
e.printStackTrace();
}
request.getRequestDispatcher("success.jsp").forward(request, response);
}
//要在WebRoot下建立upload文件夹,并在lib下导入两个包
上传成功后,可以在tomcat下你项目里的upload文件夹中找到上传的文件
二、下载文件
1.jsp页面中通过a链接下载
<a href="down.do?filename=测试.docx">测试.docx</a>
2.建立DownloadServlet
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("utf-8");
response.setContentType("application/x-msdownload;");
String fileName=request.getParameter("filename");
System.out.println("下载的文件为:"+new String(fileName.getBytes("iso8859-1"),"UTF-8"));
String filePath=request.getRealPath("/upload");
//浏览器下载时默认保存的文件名称
response.setHeader("Content-disposition", "attachment; filename=\"" + fileName+"\"");
InputStream is=new FileInputStream(new File(filePath+"/"+new String(fileName.getBytes("iso8859-1"),"UTF-8")));
//得到浏览器响应的输出流
OutputStream os=response.getOutputStream();
byte data[]=new byte[1024*1024*10];
int length=0;
while(is.available()>0){
length=is.read(data);
}
os.write(data,0,length);
os.flush();
}
//因为a链接默认使用get方法,所以传过来的fileName要重新编码成utf-8,否则会出现乱码