zoukankan      html  css  js  c++  java
  • Java实现上传下载

    一、上传

    二、下载

     1 import java.io.BufferedInputStream;
     2 import java.io.BufferedOutputStream;
     3 import java.io.File;
     4 import java.io.FileInputStream;
     5 import java.io.IOException;
     6 import java.io.InputStream;
     7 import java.io.OutputStream;
     8 import java.net.URLEncoder;
     9 
    10 import javax.servlet.http.HttpServletResponse;
    11 
    12 public class DownloadFileUtil {
    13     /**
    14      * 弹窗下载
    15      * @param response
    16      * @param filePath
    17      *            文件所在路径
    18      * @param fileName
    19      *            文件名
    20      */
    21     public void downFile(HttpServletResponse response, String filePath,
    22             String fileName) {
    23         try {
    24             String path = filePath + fileName;
    25             File file = new File(path);
    26             if (file.exists()) {
    27                 InputStream ins = new FileInputStream(path);
    28                 BufferedInputStream bins = new BufferedInputStream(ins);// 放到缓冲流里面
    29                 OutputStream outs = response.getOutputStream();// 获取文件输出IO流
    30                 BufferedOutputStream bouts = new BufferedOutputStream(outs);
    31                 response.setContentType("application/x-download");// 设置response内容的类型
    32                 response.setHeader("Content-disposition","attachment;filename="
    33                                 + URLEncoder.encode(fileName, "GBK"));// 设置头部信息
    34                 int bytesRead = 0;
    35                 byte[] buffer = new byte[8192];
    36                 // 开始向网络传输文件流
    37                 while ((bytesRead = bins.read(buffer, 0, 8192)) != -1) {
    38                     bouts.write(buffer, 0, bytesRead);
    39                 }
    40                 bouts.flush();// 这里一定要调用flush()方法
    41                 ins.close();
    42                 bins.close();
    43                 outs.close();
    44                 bouts.close();
    45             }
    46         } catch (IOException e) {
    47             e.printStackTrace();
    48         }
    49     }
    50 }

    有一篇不错的文章:http://blog.csdn.net/chow__zh/article/details/9288793#comments

  • 相关阅读:
    C语言 · 阶乘计算 · 基础练习
    C语言 · 查找整数 · 基础练习
    UML课程复习重点
    运维参考
    mysql语法总结
    Python杂篇
    Python练习题
    Python参考
    k8s中ipvs和iptables选择
    安装cni网络插件-非必须
  • 原文地址:https://www.cnblogs.com/zhaoyhBlog/p/6256128.html
Copyright © 2011-2022 走看看