在好例子网,分享、交流、成长!
您当前所在位置:首页Java 开发实例Java语言基础 → jsp 上传下载文件 实例源码

jsp 上传下载文件 实例源码

Java语言基础

下载此实例
  • 开发语言:Java
  • 实例大小:0.51M
  • 下载次数:67
  • 浏览次数:363
  • 发布时间:2016-12-16
  • 实例类别:Java语言基础
  • 发 布 人:lasdasdas
  • 文件格式:.zip
  • 所需积分:6
 相关标签: upload

实例介绍

【实例简介】

【实例截图】

【核心代码】


package com.syz.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.ProgressListener;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;


public class UploadService extends HttpServlet {

    public static final String LIST = "/list";

    public static final String FORM = "/form";

    public static final String HANDLE = "/handle";

    public static final String DOWNLOAD = "/download";

    public static final String DELETE = "/delete";

    public static final String UPLOAD_DIR = "/upload";

    private static final long serialVersionUID = 2170797039752860765L;

    public void execute(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        System.out.println("execute...");
        System.out.println("------------begin---------------");
        req.setCharacterEncoding("UTF-8");
        String host = req.getRemoteHost();
        System.out.println("host:"   host);
        String uri = req.getRequestURI();
        System.out.println("uri:"   uri);
        ServletContext servletContext = this.getServletConfig()
                .getServletContext();
        // 上传文件的基本路径
        String basePath = servletContext.getRealPath(UPLOAD_DIR);
        // 上下文路径
        String contextPath = servletContext.getContextPath();
        System.out.println("contextPath:"   contextPath);
        // 截取上下文之后的路径
        String action = uri.substring(contextPath.length());
        System.out.println("action:"   action);
        // 依据action不同进行不同的处理
        if (action.equals(FORM)) {
            form(contextPath, resp);
        }
        else if (action.equals(HANDLE)) {
            boolean isMultipart = ServletFileUpload.isMultipartContent(req);
            System.out.println("isMultipart:"   isMultipart);
            if (!isMultipart) {
                return;
            }
            DiskFileItemFactory factory = new DiskFileItemFactory();
            File repository = (File) servletContext
                    .getAttribute(ServletContext.TEMPDIR);
            System.out.println("repository:"   repository.getAbsolutePath());
            System.out.println("basePath:"   basePath);
            factory.setSizeThreshold(1024 * 100);
            factory.setRepository(repository);
            ServletFileUpload upload = new ServletFileUpload(factory);
            // 创建监听
            ProgressListener progressListener = new ProgressListener() {
                public void update(long pBytesRead, long pContentLength,
                        int pItems) {
                    System.out.println("当前文件大小:"   pContentLength   "\t已经处理:"
                              pBytesRead);
                }
            };
            upload.setProgressListener(progressListener);
            List<FileItem> items = null;
            try {
                items = upload.parseRequest(req);
                System.out.println("items size:"   items.size());
                Iterator<FileItem> ite = items.iterator();
                while(ite.hasNext()){
                    FileItem item = ite.next();
                    if(item.isFormField()){
                        // handle FormField
                    }else{
                        // handle file
                        String fieldName = item.getFieldName();
                        String fileName = item.getName();
                        fileName = fileName.substring(
                                fileName.lastIndexOf(File.separator)   1);
                        String contentType = item.getContentType();
                        boolean isInMemory = item.isInMemory();
                        long sizeInBytes = item.getSize();
                        System.out.println(fieldName   "\t"   fileName   "\t"
                                  contentType   "\t"   isInMemory   "\t"
                                  sizeInBytes);
                        File file = new File(
                                basePath   "/"   fileName   "_"   getSuffix());
                        // item.write(file);
                        InputStream in = item.getInputStream();
                        OutputStream out = new FileOutputStream(file);
                        byte[] b = new byte[1024];
                        int n = 0;
                        while ((n = in.read(b)) != -1) {
                            out.write(b, 0, n);
                        }
                        out.flush();
                        in.close();
                        out.close();
                    }
                }
                // 处理完后重定向到文件列表页面
                String href1 = contextPath   LIST;
                resp.sendRedirect(href1);
            }
            catch (FileUploadException e) {
                e.printStackTrace();
            }
            catch (Exception e) {
                e.printStackTrace();
            }
        }
        else if (action.equals(LIST)) {
            list(contextPath, basePath, resp);
        }
        else if (action.equals(DOWNLOAD)) {
            String id = req.getParameter("id");
            System.out.println("id:"   id);
            if (id == null) {
                return;
            }
            File file = new File(basePath);
            File[] list = file.listFiles();
            int len = list.length;
            boolean flag = false;
            for (int i = 0; i < len; i  ) {
                File f = list[i];
                String fn = f.getName();
                if (f.isFile() && fn.lastIndexOf("_") > -1) {
                    String fid = fn.substring(fn.lastIndexOf("_"));
                    if (id.equals(fid)) {
                        download(f, resp);
                        flag = true;
                        break;
                    }
                }
            }
            if (!flag) {
                notfound(contextPath, resp);
            }
        }
        else if (action.equals(DELETE)) {
            String id = req.getParameter("id");
            System.out.println("id:"   id);
            if (id == null) {
                return;
            }
            File file = new File(basePath);
            File[] list = file.listFiles();
            int len = list.length;
            boolean flag = false;
            for (int i = 0; i < len; i  ) {
                File f = list[i];
                String fn = f.getName();
                if (f.isFile() && fn.lastIndexOf("_") > -1) {
                    String fid = fn.substring(fn.lastIndexOf("_"));
                    if (id.equals(fid)) {
                        f.delete();
                        flag = true;
                        break;
                    }
                }
            }
            if (flag) {
                // 处理完后重定向到文件列表页面
                String href1 = contextPath   LIST;
                resp.sendRedirect(href1);
            }
            else {
                notfound(contextPath, resp);
            }
        }
        else {
            show404(contextPath, resp);
        }
        System.out.println("------------end---------------");
    }

    private void show404(String contextPath, HttpServletResponse resp)
            throws IOException {
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter out = resp.getWriter();
        String href1 = contextPath   LIST;
        out.write("<html>");
        out.write("<head><title>404</title></thead>");
        out.write("<body>");
        out.write("<b>您所访问的页面不存在!<a href='"   href1   "'>点击</a>返回文件列表</b>");
        out.write("</body>");
        out.write("</html>");
        out.close();
    }

    private void form(String contextPath, HttpServletResponse resp)
            throws IOException {
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter out = resp.getWriter();
        String href1 = contextPath   LIST;
        out.write("<html>");
        out.write("<head><title>form</title></thead>");
        out.write("<body>");
        out.write("<b><a href='"   href1   "'>点击</a>返回文件列表</b>");
        out.write(
                "<form action='handle' method='post' enctype='multipart/form-data' style='margin-top:20px;'>");
        out.write("<input name='file' type='file'/><br>");
        out.write("<input type='submit' value='上传'/><br>");
        out.write("</form>");
        out.write("</body>");
        out.write("</html>");
        out.close();
    }

    private void notfound(String contextPath, HttpServletResponse resp)
            throws IOException {
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter out = resp.getWriter();
        String href1 = contextPath   LIST;
        out.write("<html><body><b>操作失败!文件不存在或文件已经被删除!<a href='"   href1
                  "'>点击</a>返回文件列表</b></body></html>");
        out.close();
    }

    private void download(File f, HttpServletResponse resp)
            throws IOException {
        String fn = f.getName();
        String fileName = fn.substring(0, fn.lastIndexOf("_"));
        System.out.println("fileName:"   fileName);
        resp.reset();
        resp.setContentType("application/octet-stream");
        String encodingFilename = new String(fileName.getBytes("GBK"),
                "ISO8859-1");
        System.out.println("encodingFilename:"   encodingFilename);
        resp.setHeader("content-disposition",
                "attachment;filename="   encodingFilename);
        InputStream in = new FileInputStream(f);
        OutputStream out = resp.getOutputStream();
        byte[] b = new byte[1024];
        int n = 0;
        while ((n = in.read(b)) != -1) {
            out.write(b, 0, n);
        }
        out.flush();
        in.close();
        out.close();
    }

    private void list(String contextPath, String basePath,
            HttpServletResponse resp)
            throws IOException {
        String href_u = contextPath   FORM;
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter out = resp.getWriter();
        out.write("<html>");
        out.write("<head><title>list</title></thead>");
        out.write("<body>");
        out.write("<b>我要<a href='"   href_u   "'>上传</a></b><br>");
        out.write(
                "<table border='1' style='border-collapse:collapse;width:100%;margin-top:20px;'>");
        out.write("<thead>");
        out.write("<tr>");
        out.write("<th>序号</th><th>文件名</th><th>操作</th>");
        out.write("</tr>");
        out.write("</thead>");
        out.write("<tbody>");
        File file = new File(basePath);
        File[] list = file.listFiles();
        System.out
                .println("basePath:"   basePath   "\tlist.size:"   list.length);
        int len = list.length;
        int no = 1;
        for (int i = 0; i < len; i  ) {
            File f = list[i];
            System.out.println(i   "\t"   f.getName());
            String fn = f.getName();
            if (f.isFile() && fn.lastIndexOf("_") > -1) {
                String filename = fn.substring(0, fn.lastIndexOf("_"));
                String id = fn.substring(fn.lastIndexOf("_"));
                String href1 = contextPath   DOWNLOAD   "?id="   id;
                String href2 = contextPath   DELETE   "?id="   id;
                StringBuilder sb = new StringBuilder();
                sb.append("<tr>");
                sb.append("<td>");
                sb.append(no  );
                sb.append("</td>");
                sb.append("<td>");
                sb.append(filename);
                sb.append("</td>");
                sb.append("<td>");
                sb.append("<a href='");
                sb.append(href1);
                sb.append("'>下载</a>&nbsp;<a href='");
                sb.append(href2);
                sb.append("' onclick='return confirm(\"您确定要删除吗?\");'>删除</a>");
                sb.append("</td>");
                sb.append("</tr>");
                out.write(sb.toString());
            }
        }
        out.write("</tbody>");
        out.write("</table>");
        out.write("</body>");
        out.write("</html>");
        out.close();
    }

    public void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        System.out.println("doGet...");
        execute(req, resp);
    }

    public void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        System.out.println("doPost...");
        execute(req, resp);
    }

    private String getSuffix() {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String suffix = sdf.format(date);
        return suffix;
    }
}


标签: upload

实例下载地址

jsp 上传下载文件 实例源码

不能下载?内容有错? 点击这里报错 + 投诉 + 提问

好例子网口号:伸出你的我的手 — 分享

网友评论

第 1 楼 本人新手小白 发表于: 2016-12-22 18:13 36
谢谢,很不错

支持(0) 盖楼(回复)

发表评论

(您的评论需要经过审核才能显示)

查看所有1条评论>>

小贴士

感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。

  • 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
  • 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
  • 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
  • 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。

关于好例子网

本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明

;
报警