Servlet和Jsp实现原生的上传与下载文件

1.01.jsp 前台代码

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP '01.jsp' starting page</title>
    
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">    
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
  </head>
  <body>
  <form action="uploadServlet.do" method="post" enctype="multipart/form-data">//

<!--这里注意下 表单中enctype="multipart/form-data"的意思,是设置表单的MIME编码。默认情况,这个编码格式是application/x-www-form-urlencoded,不能用于文件上传;只有使用了multipart/form-data,才能完整的传递文件数据,进行下面的操作. 
enctype="multipart/form-data"是上传二进制数据; form里面的input的值以2进制的方式传过去 -->
  请选择文件:<input id="myfile" name="myfile" type="file" οnchange="showPreview(this)"/>
  <input type="submit" value="提交"  />${result}
  </form>
  下载:<a href="downloadServlet.do?filename=xxx.txt">xxx.txt</a> &nbsp;&nbsp; ${errorResult}//下载文件这里名字我写死了,但是用JS方法应该能实现动态下载文件功能
  
  <div id="large"></div>
  
  
  </body>
</html>


2.后台代码 UploadServlet.java

package com.imooc.servlet;


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
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 req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req,resp);
}


public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//req.setCharacterEncoding("text/html;charset=UTF-8");
//从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");//RandomAccessFile是用来访问那些保存数据记录的文件的,第二个参数“r”表示只读。
randomFile.readLine();//读取第一行数据
String str = randomFile.readLine();//读取第二行数据,为什么读取了两次,看临时文件的保存的内容便知,第一行,和最后一行都是无用的内容数据,所以直接从第二行读取。


String str1 = str.substring(0,str.lastIndexOf("\""));//根据最后一个引号来定位
int endIndex = str.lastIndexOf("\"");
int beginIndex = str1.lastIndexOf("\"")+1 ;//beginIndex,endIndex,得到文件name 的初始位置。

String filename = str.substring(beginIndex, endIndex);


filename=new String(filename.getBytes("ISO-8859-1"),"utf-8");//因为从记事本中读取出来的是ISO-8859-1,所以需要转码,防止乱码

System.out.println("filename:" + filename);

//重新定位文件指针到文件头
randomFile.seek(0);// seek方法可以在文件中移动。
long startPosition = 0;
int i = 1;
//获取文件内容 开始位置
while(( n = randomFile.readByte()) != -1 && i <=4){
if(n == '\n'){
startPosition = randomFile.getFilePointer()//.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);
}
}

3.DownloadServlet.java 下载文件

package com.imooc.servlet;


import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;


import javax.servlet.RequestDispatcher;
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 req, HttpServletResponse resp)
throws ServletException, IOException {
//获取文件下载路径
String path = getServletContext().getRealPath("/") + "images/";
String filename = req.getParameter("filename");
filename=new String(filename.getBytes("ISO-8859-1"),"utf-8");
System.out.println(filename);

System.out.println("filename:"+filename);
File file = new File(path + filename);
if(file.exists()){
//设置相应类型application/octet-stream
resp.setContentType("application/x-msdownload");
//设置头信息
filename = new String(filename.getBytes("utf-8"),"ISO-8859-1");//将数据写入到记事本,需要转码,这和上传文件刚好那个步骤刚好相反
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);
}


}


public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doGet(req,resp);
}


}

项目目录


配置文件


有兴趣的朋友可以试试,以后做小型项目可以直接拿来用了。

下一篇则是使用SmartUpload工具简化jsp下载,但是先学原生的jsp实现学会原理更好。

  • 5
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值