最近Java项目上有个文件上传的功能需求,当然有上传就存在对应的下载需求。由于项目的框架由前辈搭建好了,对于功能上的需求就直接往框架中添加模块,完全采用CTRL+C/V的方式在已有的代码上做相应的修改,没撒技术含量,就这个小的功能需求对于目前这种景况也算是一个插曲 – 需要自己实现。
通过多天的代码编写与测试,终于完成对上传/下载的实现,先将其过程详细记录,以备后续总结。
工具:JBuilder 2006
WEB环境:tomcat 5.5(可以是JBuilder2006自带,亦可以是单独的tomcat软件)
实现方式:主要采用Servlet方式完成。
首先,实现Servlet代码如下:
上传代码:
- package com.vspeed.servlet.util;
- import javax.servlet.http.*;
- import java.io.*;
- public class ToolUpload extends HttpServlet {
- public ToolUpload() {
- super();
- }
- //该方法完成对一个或一个以上文件的上传,无大小,格式限制
- public void doGet(HttpServletRequest request, HttpServletResponse response) {
- response.setCharacterEncoding("GBK");
- try {
- javax.servlet.ServletInputStream input = request.getInputStream();
- String direct = getServletContext().getRealPath("\\") + "files", //设置服务器附件保存文件夹
- //path = request.getRequestURI();//该方法在1.2以后就不建议使用
- path = path.substring(0, path.indexOf("/servlet"));
- java.io.File file = new java.io.File(direct);
- if (!file.exists()) file.mkdir(); //不存在文件夹则创建
- long fileName = System.currentTimeMillis();//获取系统时间,保证文件名的唯一性
- DataOutputStream pw = null;
- byte[] content = new byte[request.getContentLength()];
- int length = input.readLine(content, 0, content.length), loop = 1; //获取第一行信息
- java.util.Map<String, String> map = new java.util.HashMap<String, String>();
- String head = new String(content, 0, length - 1).replaceAll("-", "").replaceAll("\r", ""); //第一行字符串
- String tmpFileName = "", strExtentType = "";
- while ((length = input.readLine(content, 0, content.length)) != -1) { //获取上传文件名
- tmpFileName = new String(content, 0, length - 1);
- tmpFileName = tmpFileName.substring(tmpFileName.lastIndexOf("\\") + 1);
- strExtentType = tmpFileName.substring(tmpFileName.lastIndexOf("."));
- if (!map.containsKey(fileName + "-" + String.format("%03d", loop)))
- map.put(fileName + "-" + String.format("%03d", loop), tmpFileName.replaceAll("\"", ""));
- input.readLine(content, 0, content.length);
- input.readLine(content, 0, content.length);
- tmpFileName = direct + "\\" + fileName + "-" + String.format("%03d", loop) + strExtentType.replaceAll("\"\r", "");
- pw = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(tmpFileName)));
- while ((length = input.readLine(content, 0, content.length)) != -1) {
- if ((new String(content, 0, length - 1)).indexOf(head) > 0) break;
- pw.write(content, 0, length);
- }
- pw.close();
- pw = null;
- loop++;
- }
- if (pw != null) pw.close();
- response.getWriter().println("<center><hl>Test For Upload File(s)</h1>");
- response.getWriter().println("<hr />");
- String label = "文件上传成功!\\n完成" + map.size() + "个文件的上传";
- if (map.size() == 0) label = "文件上传失败!";
- if (map.size() > 0) {
- response.getWriter().println("<table><thead>" + "<tr><td colspan=3 align=center>上传文件信息</td></tr>" +
- "<tr><td align=center>序号</td><td align=center>上传后的文件名</td>" +
- "<td align=center>上传文件名</td></tr></thead><tbody>");
- for (loop = 0; loop < map.keySet().toArray().length; loop++) {
- response.getWriter().println("<tr><td align=center>" + (loop + 1) + "</td>");
- String key = (String) map.keySet().toArray()[loop], name = map.get(key);
- response.getWriter().println("<td>" + key + "</td>");
- response.getWriter().println("<td><a href='/util/servlet/download?FileName=" + key + "." + name.substring(name.lastIndexOf(".") + 1) + "' >" + name + "</a></td>");
- response.getWriter().println("</tr>");
- }
- response.getWriter().println("</tbody></table></center>");
- }
- response.getWriter().println("<script>alert('" + label + "');</script>");
- } catch (Exception ex) {
- ex.printStackTrace();
- }
- }
- public void doPost(HttpServletRequest request, HttpServletResponse response) {
- doGet(request, response);
- }
- public void process(HttpServletRequest request,
- HttpServletResponse response) {
- doGet(request, response);
- }
- }
下载:
- package com.vspeed.servlet.util;
- import javax.servlet.http.*;
- import java.net.URLEncoder;
- public class ToolDownLoad extends HttpServlet {
- public ToolDownLoad(){super();}
- //完成下载功能
- public void doGet(HttpServletRequest request, HttpServletResponse response){
- response.setCharacterEncoding("GBK");
- try{
- String strFile = request.getParameter("FileName");
- String path = getServletContext().getRealPath("\\") + "files";
- java.io.File file = new java.io.File(path + "\\" + strFile);
- if(!file.exists()){response.getWriter().println("<script>alert('附件信息不存在!'); </script>");return;}
- response.setContentType("application/x-msdownload"); //设置格式
- response.setHeader("Content-Dispostion", "attchment;filename=" + strFile + "");
- java.io.FileInputStream input = new java.io.FileInputStream(file);
- int length = input.available();
- byte[] content = new byte[length];
- input.read(content);
- javax.servlet.ServletOutputStream out = response.getOutputStream();
- out.write(content);
- input.close();
- out.close();
- }catch(Exception ex){ex.printStackTrace();}
- }
- public void doPost(HttpServletRequest request, HttpServletResponse response){
- doGet(request, response);
- }
- public void process(HttpServletRequest request, HttpServletResponse response){
- doPost(request, response);
- }
- }
其次、配置Servlet,代码如下:
- <servlet>
- <!—上传 -->
- <servlet-name>UtilUpload</servlet-name>
- <servlet-class>com.vspeed.servlet.util.ToolUpload</servlet-class>
- </servlet>
- <servlet-mapping>
- <servlet-name>UtilUpload</servlet-name>
- <url-pattern>/servlet/upload</url-pattern><!—注意这里的url-pattern的配置必须为/servlet/* -->
- </servlet-mapping>
- <!—下载 -->
- <servlet>
- <servlet-name>ToolDownLoad</servlet-name>
- <servlet-class>com.vspeed.servlet.util.ToolDownLoad</servlet-class>
- </servlet>
- <servlet-mapping>
- <servlet-name>ToolDownLoad</servlet-name>
- <url-pattern>/servlet/download</url-pattern>
- </servlet-mapping>
最后、页面代码,这里我主要采用javascript代码动态添加上传附件组件,代码如下:
- <%@ page contentType="text/html; charset=GBK" %>
- <html>
- <head>
- <title>
- Test4Upload
- </title>
- <script type="text/javascript">
- var fileName = <%=System.nanoTime() %>;
- function addItem(){
- var item = document.createElement('INPUT');
- item.type = 'file';
- var items = cpanel.rows.length;
- item.name = fileName + '-'+items ; //注意这里一定要设置组件的name属性,form文件上传只认name属性,理论上讲id也应该可以的,希望有朋友能帮忙解释哈,先谢~~~~~~
- item.id = 'file' + items;
- var tr = cpanel.insertRow();
- var cell = document.createElement('TD');
- cell.align = 'right';
- cell.innerText = '附件' + items + ':';
- tr.appendChild(cell);
- cell = document.createElement('TD');
- cell.appendChild(item);
- tr.appendChild(cell);
- }
- </script>
- </head>
- <body bgcolor="#ffffff">
- <center>
- <h2>
- JBuilder Generated JSP -- Test For Upload File(s)
- </h2>
- <h3>测试时间:<%=new java.util.Date() %></h3>
- <hr />
- <form method="post" action="/util/servlet/upload" enctype="multipart/form-data"><!-- 定要设置为multipart/form-data,上传文件必须为该类型 -->
- <table id=cpanel>
- <tr style='display:none'><td> </td><td> </td>
- </tr>
- </table>
- <button id='btnAdd' onclick=addItem()>添加(T)</button>
- <input type=submit value=submit /><!--定要有该组件,并且不能通过javascript函数来完成点击 -->
- </form>
- </center>
- <div id="divDetail"></div>
- </body>
- </html>
效果图如下:
文件上传界面
上传完成界面
注意,最后一列提供查看下载功能。
直接点击查看界面
右键另存为界面
本文出自 “好记性不如烂笔头” 博客,请务必保留此出处http://tener.blog.51cto.com/1065457/729257