欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2024-02-11 21:41:28
一丶先引入上传下载的lib 二丶上传的的servlet package com.test.action; import java.io.file; im...

一丶先引入上传下载的lib

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<fileitem> list = (list<fileitem>) 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中上传和下载文件实例代码,希望对大家有所帮助