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

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

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

java文件上传下载代码实例

2021-07-22 16:24弓长张&木子李 Java教程

这篇文章主要介绍了java文件上传下载,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

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

文件上传

?
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
@requestmapping(value="/uploadfile",method=requestmethod.post)
 public resultobject uploadfiles(@requestparam("file")multipartfile file,httpservletrequest request){
    resultobject rs = null;//返回上传完成信息
    string uploaddir = "files";//上传目录,文件保存在webapp下的files文件中
   if(!file.isempty()) {
     //可以对user做一些操作如存入数据库
     //以下的代码是将文件file重新命名并存入tomcat的webapp目录下项目的下级目录
     string filerealname = file.getoriginalfilename();          //获得原始文件名;
     /*int pointindex = filerealname.indexof(".");            //点号的位置
     string filesuffix = filerealname.substring(pointindex);       //截取文件后缀
     uuid fileid = uuid.randomuuid();            //生成文件的前缀包含连字符
     string savedfilename = fileid.tostring().replace("-", "").concat(filesuffix);    //文件存取名
     */
     
     string saveddir = request.getsession().getservletcontext().getrealpath(uploaddir); //获取服务器指定文件存取路径
     file savedfile = new file(saveddir, filerealname);
     boolean iscreatesuccess;
     try {
       iscreatesuccess = savedfile.createnewfile();
       if (iscreatesuccess) {
 
         file.transferto(savedfile); //转存文件
         rs = resultobject.getsuccessresult("上传文件成功");
         long size = file.getsize();//获取文件大小
 
 
         rs.setdata(uploaddir+filerealname);
       }else{
         rs = resultobject.getfailresult("请修改文件名,重新上传");
       }
     } catch (ioexception e) {
       e.printstacktrace();
     }
   }else{
     rs = resultobject.getfailresult("文件不能为空");
   }
   return rs;
 }

文件下载

?
1
2
3
4
5
@requestmapping(value = "/filterpermission/appdownload", method = requestmethod.get)
  public void appdownload(httpservletrequest request, httpservletresponse response) {
    //url是上面文件上传的url
    download(url,request,response);
  }
?
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
public string download(string filepath, httpservletrequest request, httpservletresponse response) {
    bufferedinputstream bis = null;
    bufferedoutputstream bos = null;
    try {
      //获取文件名
      string filename = filepath.substring(filepath.lastindexof("/")+1);
      response.setcharacterencoding("utf-8");
      response.setcontenttype("application/octet-stream");
      //response.setcontenttype("application/force-download");
      //处理下载弹出框名字的编码问题
      response.setheader("content-disposition", "attachment;filename="
          + new string( filename.getbytes("gb2312"), "iso8859-1" ));
      //获取文件的下载路径
      string path = request.getsession().getservletcontext().getrealpath(filepath);
      //利用输入输出流对文件进行下载
      inputstream inputstream = new fileinputstream(new file(path));
      //设置文件大小
      response.setheader("content-length", string.valueof(inputstream.available()));
 
      bis = new bufferedinputstream(inputstream);//构造读取流
      bos = new bufferedoutputstream(response.getoutputstream());//构造输出流
      byte[] buff = new byte[1024];
      int bytesread;
      //每次读取缓存大小的流,写到输出流
      while (-1 != (bytesread = bis.read(buff, 0, buff.length))) {
        bos.write(buff, 0, bytesread);
      }
      response.flushbuffer();//将所有的读取的流返回给客户端
 
    } catch (filenotfoundexception e) {
      e.printstacktrace();
    } catch (ioexception e) {
      e.printstacktrace();
    }finally{
      try{
        if(null != bis){
          bis.close();
        }
        if(null != bos){
          bos.close();
        }
      }catch(ioexception e){
        system.out.println("下载文件失败,"+"文件路径:"+filepath+e);
        logger.error("文件下载失败!", e);
      }
    }
    // 返回值要注意,要不然就出现下面这句错误!
    //java+getoutputstream() has already been called for this response
    return null;
  }

以上所述是小编给大家介绍的java文件上传下载详解整合,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对服务器之家网站的支持!

原文链接:https://www.cnblogs.com/gczmn/p/9921479.html

延伸 · 阅读

精彩推荐