文件下载+保存本地服务器

```package com.oristand.starcloud.common.utils;

import com.oristand.starcloud.common.constants.KeyboardSpecialCharConstants;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;


/**
 * 文件下载
 *
 * @author peiyuxiang
 * @date 2021/05/04
 */
@Slf4j
public class FileDownloadUtil {

    /**
     * pdf下载流
     */
    public static final String APPLICATION_PDF = "application/pdf";
    /**
     * pdf下载流
     */
    public static final String APPLICATION_TEXT_PLAIN = "text/plain";

    /**
     * http 传输文件
     *
     * @param response servlet响应
     * @param filePath 文件全路径名
     * @param fileName 附件文件名
     */
    public static void download(HttpServletResponse response,
                                String filePath,
                                String fileName,
                                String contentType
    ) throws IOException {

        if (StringUtils.isBlank(contentType)) {
            response.setContentType("application/octet-stream");
        } else {
            response.setContentType(contentType);
        }

        try {
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "utf-8"));
        } catch (Exception e) {
            // pass
        }

        byte[] buff = new byte[1024];

        //创建缓冲输入流
        BufferedInputStream bis = null;
        OutputStream outputStream = null;

        try {
            outputStream = response.getOutputStream();

            //这个路径为待下载文件的路径
            bis = new BufferedInputStream(new FileInputStream(new File(filePath)));
            int read = bis.read(buff);

            //通过while循环写入到指定了的文件夹中
            while (read != -1) {
                outputStream.write(buff, 0, read);
                outputStream.flush();
                read = bis.read(buff);
            }
        } finally {
            if (null != bis) {
                try {
                    bis.close();
                } catch (IOException e) {
                    // 忽略
                }
            }
            if (null != outputStream) {
                try {
                    outputStream.flush();
                    outputStream.close();
                } catch (IOException e) {
                    // 忽略
                }
            }
        }
    }


    /**
     * 用http请求将url文件保存到本地
     *
     * @param url      请求文件的url
     * @param filePath 需要保存的路径
     * @return 是否保存文件成功, 成功返回true, 失败返回false
     */
    public static boolean saveFileByUrl(URL url, String filePath) {
        try {
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setConnectTimeout(10000);
            connection.setReadTimeout(10000);
            DataInputStream inputStream = new DataInputStream(connection.getInputStream());
            DataOutputStream outputStream = new DataOutputStream(new FileOutputStream(filePath));
            byte[] buffer = new byte[1024];
            int count;
            while ((count = inputStream.read(buffer)) > 0) {
                outputStream.write(buffer, 0, count);
            }
            outputStream.close();
            inputStream.close();
            log.info("this is connection success");
            return true;
        } catch (Exception e) {
            log.error("FileDownloadUtil#saveFileByUrl error url:{},filePath:{}", url, filePath);
            return false;
        }
    }

    /**
     * 将数据保存到path路径
     *
     * @param inputStream 文件流
     * @param savePath    路径:"D:\\testFile\\"
     * @param fileName    文件名:text.pdf
     */
    public static Boolean saveFileToPath(InputStream inputStream, String savePath, String fileName) {
        if (null == inputStream || StringUtils.isBlank(savePath) || StringUtils.isBlank(fileName)) {
            return false;
        }
        FileOutputStream fileOutputStream = null;
        DataOutputStream dataOutputStream = null;
        try {
            //输出的文件流保存到本地文件
            File file = new File(savePath);
            boolean flag = file.exists();
            if (!flag) {
                flag = file.mkdirs();
            }
            if (!flag) {
                return false;
            }
            String finalPath;
            if (savePath.endsWith(KeyboardSpecialCharConstants.SLASH) ||
                    savePath.endsWith(KeyboardSpecialCharConstants.BACKSLASH)) {
                finalPath = savePath + fileName;
            } else {
                finalPath = savePath + KeyboardSpecialCharConstants.SLASH + fileName;
            }

            fileOutputStream = new FileOutputStream(finalPath);
            dataOutputStream = new DataOutputStream(fileOutputStream);
            //保存到临时文件
            byte[] bs = new byte[1024];
            //读取到的数据长度
            int len;
            while ((len = inputStream.read(bs)) != -1) {
                dataOutputStream.write(bs, 0, len);
                dataOutputStream.flush();
            }
        } catch (IOException e) {
            log.error("saveFileToPath#error", e);
            return false;
        } finally {
            //完毕,关闭所有链接
            try {
                inputStream.close();
            } catch (IOException e) {
                // 忽略
            }
            if (null != fileOutputStream) {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    // 忽略
                }
            }
            if (null != dataOutputStream) {
                try {
                    dataOutputStream.close();
                } catch (IOException e) {
                    // 忽略
                }
            }
        }
        return true;
    }


    /**
     * 创建目录
     *
     * @param filePath 文件路径
     * @return true/false
     */
    public static Boolean createDirectory(String filePath) {
        if (StringUtils.isBlank(filePath)) {
            return false;
        }
        File file = new File(filePath);
        boolean flag = file.exists();
        if (!flag) {
            flag = file.mkdirs();
        }
        if (flag) {
            return true;
        }
        log.info("createDirectory Failed#filePath:{}", filePath);
        return false;
    }
}
全部评论

相关推荐

昨天 10:10
已编辑
门头沟学院 人工智能
写这篇之前我犹豫了挺久。一方面是怕被人骂,"又一个收割焦虑的转行帖";另一方面是看了太多用 GPT 套娃出来的「学习路线」文章,AI 味重得让人没法读完。所以这篇全是亲身踩过的坑,时间线、用过的项目、当时的心路全都尽量原样写出来。如果你是大学生在迷茫要不要转 AI,或者已经在转的路上,希望能给点参考。 一个反共识的开场:你以为进 OpenAI 的人都是博士? 先讲个故事,跟我没关系,但跟所有想转 AI 的人都有关系。 OpenAI 的 Sora 团队(就是搞文生视频那个)一共 13 个人。这里面有两个人特别有意思: Will DePue,密歇根大学计算机系,直接辍学了。17...
_hengheng:我也本,也算是做ai相关,我最开始感觉做ai工程师有多么多么困难,后来发现懂了原理后整体训练完全可以看成一个流程化的内容,开源方案太多了,大多基本都是按着模子在自家业务上做各种操作,就算是大厂的小部门也没那么多资源去训基模,反而更多的是像怎么把技术往业务方向靠近了,不过当前时代如果本科学历没那么好加上自己执行力不是特别强还真不建议走ai工程师这条路,可以试试其他ai的偏业务方向,不然校招不太好杀出来
点赞 评论 收藏
分享
mama3925:灵神是天才,路线不适合正常人
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务