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

java实现文件上传下载

程序员文章站 2024-02-26 15:57:28
本文实例为大家分享了java实现文件上传下载的具体代码,供大家参考,具体内容如下 一.上传 1.前端:

本文实例为大家分享了java实现文件上传下载的具体代码,供大家参考,具体内容如下

一.上传

1.前端:

<form method="post" action="fileupload" enctype="multipart/form-data">
  <input type="file" name="uploadfile" />
  <br/>
  <input type="submit" value="上传" />
</form>

2.后台:

import java.io.file;
import java.io.ioexception;
import java.io.printwriter;
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.disk.diskfileitemfactory;
import org.apache.commons.fileupload.servlet.servletfileupload;
import dao.filedao;


@webservlet("/fileupload")
public class fileupload extends httpservlet {
  private static final long serialversionuid = 1l;
   
  // 上传配置
  private static final int memory_threshold  = 1024 * 1024 * 3; // 3mb
  private static final int max_file_size   = 1024 * 1024 * 40; // 40mb
  private static final int max_request_size  = 1024 * 1024 * 50; // 50mb
  
  public fileupload() {
    super();
  }
  
  protected void doget(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {
    
    request.setcharacterencoding("utf-8");
    response.setcharacterencoding("utf-8");
    response.setcontenttype("text/html;charset=utf-8");
    printwriter out = response.getwriter();
    
      if (!servletfileupload.ismultipartcontent(request)) {
      // 如果不是则停止
      out.println("error: 表单必须包含 enctype=multipart/form-data");
      out.flush();
      return;
    }
    
    // 配置上传参数
    diskfileitemfactory factory = new diskfileitemfactory();
    // 设置内存临界值 - 超过后将产生临时文件并存储于临时目录中
    factory.setsizethreshold(memory_threshold);
    // 设置临时存储目录
    factory.setrepository(new file(system.getproperty("java.io.tmpdir")));
 
    servletfileupload upload = new servletfileupload(factory);
     
    // 设置最大文件上传值
    upload.setfilesizemax(max_file_size);
     
    // 设置最大请求值 (包含文件和表单数据)
    upload.setsizemax(max_request_size);
    
    // 中文处理
    upload.setheaderencoding("utf-8"); 
    
    
    string uploadpath = request.getservletcontext().getrealpath("/files");
    file uploaddir = new file(uploadpath);
    if (!uploaddir.exists()) {
      uploaddir.mkdir();
    }
    
    try {
      // 解析请求的内容提取文件数据
      list<fileitem> formitems = upload.parserequest(request);
      if (formitems != null && formitems.size() > 0) {
        // 迭代表单数据
        for (fileitem item : formitems) {
          // 处理不在表单中的字段
          if (!item.isformfield()) {
            string filename = new file(item.getname()).getname();
            string filepath = uploadpath + file.separator + filename;
            file storefile = new file(filepath);
            // 在控制台输出文件的上传路径
//            system.out.println(filepath);
            // 保存文件到硬盘
            if(storefile.exists()) {
              out.println("上传失败,文件已存在!");
            }else {
              item.write(storefile);
              out.println("文件上传成功!");
            }  
          }
        }
      }
    } catch (exception ex) {
      response.getwriter().println("文件上传成功!");
    }
  }

  
  protected void dopost(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {
    doget(request, response);
  }
} 

二.下载

1.下载链接:

filedownload?filename="+urlencoder.encode(filename,"utf-8") --------- 需要对url中的中文参数进行编码,否则会出现乱码

2.后台:

import java.io.file;
import java.io.fileinputstream;
import java.io.ioexception;
import java.io.printwriter;
import java.net.urlencoder;
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("/filedownload")
public class filedownload extends httpservlet {
  private static final long serialversionuid = 1l;
    
  public filedownload() {
    super();
  }

  protected void doget(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {
    
    request.setcharacterencoding("utf-8");
    response.setcharacterencoding("utf-8");
    printwriter out = response.getwriter();
    
    string dirpath = request.getservletcontext().getrealpath("/files");
    string filename = urlencoder.encode(request.getparameter("filename"),"utf-8");  //需要对url中的中文参数进行编码,否则出现乱码
    response.getwriter().println(filename);
    string filepath = dirpath + file.separator + filename;
    response.setcontenttype("application/octet-stream");
    response.setheader("content-disposition", "attachment; filename=\"" + filename + "\"");

    fileinputstream fileinputstream = new fileinputstream(filepath);
    int i = 0;
    while ((i = fileinputstream.read()) != -1) {
      out.write(i);
    }
    fileinputstream.close();
    out.close();
  }
  
  protected void dopost(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {
    doget(request, response);
  }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。