网站建设资讯

NEWS

网站建设资讯

JavaWeb中上传和下载文件实例代码-创新互联

一丶先引入上传下载的lib

创新互联主要从事成都做网站、网站设计、网页设计、企业做网站、公司建网站等业务。立足成都服务广东,十载网站建设经验,价格优惠、服务专业,欢迎来电咨询建站服务:18982081108

二丶上传的的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;
  }
}

本文标题:JavaWeb中上传和下载文件实例代码-创新互联
网站地址:http://cdweb.net/article/coccgh.html