mysql - Java从服务器端下载文件保存到本地,不是下载的图片?

 丨为你 发布于 2022-10-27 10:08
public static void downloadFile(String urlPath, String filePath) throws IOException {
        URL url = new URL(urlPath);
        String name = urlPath.substring(urlPath.lastIndexOf("=")+1);
        String filePaths = filePath+"/"+name;
        File dirFile = new File(filePath);
        if (!dirFile.exists()) {
            dirFile.mkdir();
        }
        URLConnection connection = url.openConnection();
        InputStream in = connection.getInputStream();
        FileOutputStream os = new FileOutputStream(filePaths);
        byte[] buffer = new byte[4 * 1024];
        int read;
        while ((read = in.read(buffer)) > 0) {
            os.write(buffer, 0, read);
        }
        os.close();
        in.close();
    }

    public static void main(String[] args) {
        String urlPath = "http://10.192.32.111:80/production-jcw/getDownload.do?fileName=49e23d3a-5e11-432d-9f33-91c93130b37b.dwg";
        String filePath = "C:/Users/MrLi/Desktop/";
        try {
            downloadFile(urlPath, filePath);
            System.out.println("下载成功");
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("下载失败");
        }
    }
1 个回答
  • 你参照下面这个改改就行了,希望能帮到你。

    String fileName=imagesdata.substring(imagesdata.lastIndexOf("/")+1,imagesdata.length()); 
    response.setHeader("Content-Disposition", "attachment; filename="+fileName);    response.addHeader("Content-Length", "");     
    response.setContentType("image/jpeg");   
    URL url = new URL(imagesdata);
    HttpURLConnection connection = (HttpURLConnection)url.openConnection();
    DataInputStream in = new DataInputStream(connection.getInputStream());
    DataOutputStream out = new DataOutputStream(response.getOutputStream());
                            byte[] buffer = new byte[4096];
                            int count = 0;
                            while ((count = in.read(buffer)) > 0)
                            {
                                out.write(buffer, 0, count);
                            }
                            out.close();
                            out.flush();
                            in.close();
                            connection.disconnect();
    2022-10-27 17:41 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有