服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - java实现文件上传下载

java实现文件上传下载

2021-05-29 11:34DOLFAMINGO Java教程

这篇文章主要为大家详细介绍了java实现文件上传下载功能,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

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

一.上传

1.前端:

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

2.后台:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
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.后台:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
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);
  }
}

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

原文链接:https://www.cnblogs.com/DOLFAMINGO/p/9559185.html

延伸 · 阅读

精彩推荐