快上网专注成都网站设计 成都网站制作 成都网站建设
成都网站建设公司服务热线:028-86922220

网站建设知识

十年网站开发经验 + 多家企业客户 + 靠谱的建站团队

量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决

JavaWeb中上传和下载文件实例代码

一丶先引入上传下载的lib

成都创新互联公司专注为客户提供全方位的互联网综合服务,包含不限于成都网站设计、网站建设、罗定网络推广、微信小程序开发、罗定网络营销、罗定企业策划、罗定品牌公关、搜索引擎seo、人物专访、企业宣传片、企业代运营等,从售前售中售后,我们都将竭诚为您服务,您的肯定,是我们最大的嘉奖;成都创新互联公司为所有大学生创业者提供罗定建站搭建服务,24小时服务热线:13518219792,官方网址:www.cdcxhl.com

JavaWeb中上传和下载文件实例代码

二丶上传的的servlet

package com.test.action;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
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.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
@WebServlet("/upload")
public class FileUpLoadAction extends HttpServlet {
  private static final long serialVersionUID = 1L;
  protected void doPost(HttpServletRequest request,
      HttpServletResponse response) throws ServletException, IOException {
    // 设置编码
    request.setCharacterEncoding("utf-8"); 
    //对提交的数据进行处理,保存上传文件 
    boolean success = processUpload(request);
    if(success){
      //获取表单text控件的值
      String account = request.getAttribute("account").toString();
      System.out.println(account);
      //获取文件上传的原始名称
      String fileName = request.getAttribute("upfile").toString();
      System.out.println(fileName);
      //获取文件上传后,服务器上保存的名字
      String fileNameServer = request.getAttribute("upfileServer").toString();
      System.out.println(fileNameServer);
      request.setAttribute("upfile", fileNameServer);
      request.setAttribute("message", "上传成功");
    }
    request.getRequestDispatcher("/upload.jsp").forward(request, response);
  }
  private boolean processUpload(HttpServletRequest request) {
    boolean success = true;
    String message = null;
    // 获取文件需要上传到的路径
    String path = request.getServletContext().getRealPath("/upload");
    System.out.println(path);
    // 如果此文件夹不存在,则构造此文件夹
    File f = new File(path);
    if (!f.exists()) {
      f.mkdir();
    }
    // 构造出文件工厂,用于存放JSP页面中传递过来的文件
    DiskFileItemFactory factory = new DiskFileItemFactory();
    // 设置上传文件的保存路径
    factory.setRepository(f);
    // 设置缓存大小,如果文件大于缓存大小时,则先把文件放到缓存中
    factory.setSizeThreshold(1 * 1024 * 1024);
    ServletFileUpload upload = new ServletFileUpload(factory);
    // 设置可以上传文件大小的上界20MB
    upload.setSizeMax(20 * 1024 * 1024);
    try {
      // 可以上传多个文件
      List list = (List) upload.parseRequest(request);
      for (FileItem item : list) {
        // 获取表单的属性名字
        String name = item.getFieldName();
        if (item.isFormField()) {
          String value = item.getString();
          //解决乱码问题
          value = new String(value.getBytes("iso-8859-1"),"utf-8"); 
          request.setAttribute(name, value);
        } else {
          // 获得文件类型
          String contentType = item.getContentType();
          // 获得文件大小
          long fileSize = item.getSize();
          // 获取路径名
          String value = item.getName();
          // 索引到最后一个反斜杠
          int start = value.lastIndexOf("\\");
          // 截取 上传文件的 字符串名字,加1是 去掉反斜杠,
          String filename = value.substring(start + 1);
          if (filename != null && !filename.trim().equals("")) {
            // 如果上传的文件不是图片,那么不上传
            String allImgExt = ".jpg|.jpeg|.gif|.bmp|.png|";
            String extName = filename.substring(filename.indexOf("."), filename.length());
            if (allImgExt.indexOf(extName + "|") == -1) {
              message = "该文件类型不允许上传。请上传 " + allImgExt
                  + " 类型的文件,当前文件类型为" + extName;
              success = false;
              break;
            }
            request.setAttribute(name, filename);
            // 随机数产生名称
            String newName = System.currentTimeMillis() + extName;
            request.setAttribute(name + "Server", newName);
            // 将文件保存到服务器中
            InputStream in = item.getInputStream();
            // 原文件名
            // OutputStream out = new FileOutputStream(new File(path, filename));
            // 随机数文件名
            OutputStream out = new FileOutputStream(new File(path,
                newName));
            int length = 0;
            byte[] buf = new byte[1024];
            while ((length = in.read(buf)) != -1) {
              out.write(buf, 0, length);
            }
            in.close();
            out.close();
          }
        }
      }
    } catch (FileUploadException e) {
      message = "文件的内容过大,请上传小于20MB的文件" ;
      success = false;
      e.printStackTrace();
    } catch (IOException e) {
      success = false;
      e.printStackTrace();
    }
    request.setAttribute("message", message);
    return success;
  }
}

三丶下载的servlet

package com.test.action;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/download")
public class FileDownloadAction extends HttpServlet {
  private static final long serialVersionUID = 1L;
  protected void doGet(HttpServletRequest request,
      HttpServletResponse response) throws ServletException, IOException {
    String id = request.getParameter("id");
    // 根据主键读取文件的真实名字 + 服务器上的名字
    processDownload("1444442288605.png", "腾讯.png", request, response);
  }
  private boolean processDownload(String fileName, String saveName,
      HttpServletRequest request, HttpServletResponse response) {
    boolean success = true;
    // 获取文件下载所在的路径
    String path = request.getServletContext().getRealPath("/upload");
    File fileLoad = new File(path, fileName); // 下载文件
    long fileLength = fileLoad.length(); // 文件大小
    byte[] buffer = new byte[1024]; // 缓冲字节数组
    try {
      response.reset();
      response.setHeader("Content-disposition", "attachment;filename=\""
          + new String(saveName.getBytes("gb2312"), "ISO-8859-1") + "\"");
      response.setContentType("application/octet-stream");
      response.setHeader("Content_Length", String.valueOf(fileLength));
      OutputStream os = response.getOutputStream();
      FileInputStream in = new FileInputStream(fileLoad);
      int hasRead = 0;
      while ((hasRead = in.read(buffer)) != -1) {
        os.write(buffer, 0, hasRead);
      }
      os.flush();
      os.close();
      in.close();
    } catch (IOException e) {
      success = false;
      e.printStackTrace();
    }
    return success;
  }
}

以上所述是小编给大家介绍的JavaWeb中上传和下载文件实例代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对创新互联网站的支持!


网页标题:JavaWeb中上传和下载文件实例代码
网页网址:http://6mz.cn/article/igdsci.html

其他资讯