标签:upload 文件上传 文件下载 fileupload jsp
在web程序中上传和下载是两大常用模块
上传可以利用fileupload的包来帮助完成
下载地址为:http://commons.apache.org/fileupload/。
此外FileUpload 依赖 Commons IO, 所以你需要在你的classpath中引入最新的 commons-io包, 下载地址为:http://commons.apache.org/io/。
那web程序中是如何进行上传的呢?
首先,我们建立一个uploadFile.jsp以供用户上传本地信息。
其中form表单 enctype 属性需要设置为 multipart/form-data,方法必须为post,提交处理的由fileUpload处理
<body> <p align="center">请您选择需要上传的文件</p> <form id="form1" name="form1" method="post" action="fileUpload" enctype="multipart/form-data"> <table border="0" align="center"> <tr> <td>上传人:</td> <td><input name="name" type="text" id="name" size="20"> </td> </tr> <tr> <td>上传文件:</td> <td><input name="file" type="file" size="20"> </td> </tr> <tr> <td></td> <td><input type="submit" name="submit" value="提交"> <input type="reset" name="reset" value="重置"></td> </tr> </table> </form> </body>
public class FileUploadServlet extends HttpServlet {
private static final long serialVersionUID = -7744625344830285257L;
private ServletContext sc;
private String savePath;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
public void init(ServletConfig config) {
// 在web.xml中设置的一个初始化参数
savePath = config.getInitParameter("savePath");
sc = config.getServletContext();
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//对接受过来的数据设置编码
request.setCharacterEncoding("UTF-8");
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List<FileItem> items = upload.parseRequest(request);
Iterator<FileItem> itr = items.iterator();
while (itr.hasNext()) {
FileItem item = (FileItem) itr.next();
if (item.isFormField()) {
System.out.println("表单参数名:" + item.getFieldName()
+ ",表单参数值:" + item.getString("UTF-8"));
} else {
if (item.getName() != null && !item.getName().equals("")) {
System.out.println("上传文件的大小:" + item.getSize());
System.out.println("上传文件的类型:" + item.getContentType());
// item.getName()返回上传文件在客户端的完整路径名称
System.out.println("上传文件的名称:" + item.getName());
File tempFile = new File(item.getName());
// 上传文件的保存路径
File file = new File(sc.getRealPath("/") + savePath,tempFile.getName());
item.write(file);
request.setAttribute("upload.message", "上传文件成功!");
} else {
request.setAttribute("upload.message", "没有选择上传文件!");
}
}
}
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
request.setAttribute("upload.message", "上传文件失败!");
}
request.getRequestDispatcher("/uploadResult.jsp").forward(request,
response);
}
}上传以后会跳转到uploadResult.jsp页面<body>
${requestScope['upload.message'] }
<a href="http://localhost:4848/webExercise/UploadFile.jsp">上传文件</a>
</body> <servlet>
<servlet-name>FileUploadServlet</servlet-name>
<servlet-class>com.qzp.servlet.FileUploadServlet</servlet-class>
<!--设置初始化参数-->
<init-param>
<param-name>savePath</param-name>
<param-value>uploads</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>FileUploadServlet</servlet-name>
<url-pattern>/fileUpload</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>DownloadServlet</servlet-name>
<servlet-class>com.qzp.servlet.FileDownloadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DownloadServlet</servlet-name>
<url-pattern>/FileDownServlet</url-pattern>
</servlet-mapping>
首先如果直接给用户一个链接,以供下载,这样是可行的,但是存在一些不安全的因素,比如暴露了服务器的文件存放的地址
因而,我们采用如下的方法,来进行文件下载
这是文件下载的jsp页面,
<body>
<%-- 为什么要写在out对象之中呢? 因为直接写在jsp页面中,会暴露服务器的地址 --%>
<%
String filename=null;
session.setAttribute("333.txt",filename);
//取得文件名
// filename=getFilepath().substring(mb.getFilepath().lastIndexOf("/")+1);
out.println("<td><a href=FileDownServlet?filename=333.txt>txt文件</a></td>");//java.rar这个可以改成变量
out.println("<td><a href=FileDownServlet?filename=a.txt>普通文件</a></td>");
out.println("<td><a href=FileDownServlet?filename=area.xml>xml配置文件</a></td>");
out.println("</tr>");
// }
%>
</body>public class FileDownloadServlet extends HttpServlet {
private static final String CONTENT_TYPE = "text/html; charset=utf-8";
//Initialize global variables
public void init() throws ServletException {
}
//Process the HTTP Get request
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType(CONTENT_TYPE);
//得到下载文件的名字
//String filename=request.getParameter("filename");
//解决中文乱码问题
String filename=new String(request.getParameter("filename").getBytes("iso-8859-1"),"utf-8");
//创建file对象
File file=new File("this.getServletContext().getRealPath("/")+"uploads/"+filename);
//设置response的编码方式
response.setContentType("application/x-msdownload");
//写明要下载的文件的大小
response.setContentLength((int)file.length());
//设置附加文件名
// response.setHeader("Content-Disposition","attachment;filename="+filename);
//解决中文乱码
response.setHeader("Content-Disposition","attachment;filename="+new String(filename.getBytes("utf-8"),"iso-8859-1"));
//读出文件到i/o流
FileInputStream fis=new FileInputStream(file);
BufferedInputStream buff=new BufferedInputStream(fis);
byte [] b=new byte[1024];//相当于我们的缓存
long k=0;//该值用于计算当前实际下载了多少字节
//从response对象中得到输出流,准备下载
OutputStream myout=response.getOutputStream();
//开始循环下载
while(k<file.length()){
int j=buff.read(b,0,1024);
k+=j;
//将b中的数据写到客户端的内存
myout.write(b,0,j);
}
//将写入到客户端的内存的数据,刷新到磁盘
myout.flush();
}
//Process the HTTP Post request
public void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
doGet(request, response);
}
//Clean up resources
public void destroy() {
}
}上传文件的效果图:
下载文件的效果图:
标签:upload 文件上传 文件下载 fileupload jsp
原文地址:http://blog.csdn.net/qzp1991/article/details/39028307