JAVA下载图片

测试用例如下, 所有数据是字节传输,可以下载任务文件(有权限)

    @Test
    public void test() throws Exception{
        // 获取媒体文件的输入流(读取文件)
        String mediaFileUrl = "http://img10.360buyimg.com/imgzone/jfs/t1/64129/40/1652/208494/5d0062fdE5b875f8f/1336f14c55be3ef8.jpg";
        URL mediaUrl = new URL(mediaFileUrl);
        HttpURLConnection mediaConn = (HttpURLConnection) mediaUrl.openConnection();
        mediaConn.setDoOutput(true);
        mediaConn.setRequestMethod("GET");
        // 从请求头中获取内容类型
        String contentType = mediaConn.getHeaderField("Content-Type");
        // 根据内容类型判断文件扩展名
        String fileExt = CommonUtils.getFileExt(contentType);
        BufferedInputStream bis = new BufferedInputStream(mediaConn.getInputStream());
        String file = "D:/test/download/" + UUID.randomUUID().toString() + "." + fileExt;
        OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(file));
        byte[] buf = new byte[8192];
        int size = 0;
        while ((size = bis.read(buf)) != -1) {
            // 将媒体文件写到输出流
            outputStream.write(buf, 0, size);
        }
        outputStream.close();
        bis.close();
        mediaConn.disconnect();
        System.out.println("Fin");
    }

 文件byte实际大小,并一次性输出流

    @Test
    public void test3() throws Exception{
        // 获取媒体文件的输入流(读取文件)
        String mediaFileUrl = "http://img10.360buyimg.com/imgzone/jfs/t1/40966/18/6468/250346/5d0062fdE2ad7d274/8f71146ab69ffa56.jpg";
        URL mediaUrl = new URL(mediaFileUrl);
        HttpURLConnection mediaConn = (HttpURLConnection) mediaUrl.openConnection();
        mediaConn.setDoOutput(true);
        mediaConn.setRequestMethod("GET");
//        int length = mediaConn.getContentLength();
//        System.out.println("getContentLengthLong:" + mediaConn.getContentLengthLong());
//        System.out.println("getContentLength:" + length);
        // 从请求头中获取内容类型
        String contentType = mediaConn.getHeaderField("Content-Type");
        // 根据内容类型判断文件扩展名
        String fileExt = CommonUtils.getFileExt(contentType);
        BufferedInputStream bis = new BufferedInputStream(mediaConn.getInputStream());
        String file = "D:/test/download-64/" + UUID.randomUUID().toString() + "." + fileExt;
        OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(file));
        byte[] buf = new byte[8192];
        int size = 0;
        ByteBuffer byteBuffer = ByteBuffer.allocate(250346*3);
        while ((size = bis.read(buf)) != -1) {
            // 将媒体文件写到输出流
            outputStream.write(buf, 0, size);
            byteBuffer.put(buf, 0, size);
        }
        System.out.println("byteBuffer position2 limit:" + byteBuffer.limit());
        byteBuffer.flip();
        byte[] target = new byte[byteBuffer.limit()];
        byteBuffer.get(target);
        System.out.println("byteBuffer position end:" + byteBuffer.position());
        System.out.println("target length end:" + target.length);

        String file2 = "D:/test/download-64/" + UUID.randomUUID().toString() + "PPP." + fileExt;
        OutputStream outputStream2 = new BufferedOutputStream(new FileOutputStream(file2));
        outputStream2.write(target);
        outputStream2.close();

        outputStream.close();
        bis.close();
        mediaConn.disconnect();
        System.out.println("Fin");
    }

 

Java下载图片到本地出现损坏的问题,可能有多种原因,以下结合参考内容及常见情况给出解决办法: ### 编码问题 在使用base64编码保存图片时,可能因编码不一致导致图片显示马赛克或破损打不开。在处理文件路径或内容时,确保编码统一。例如在使用ftp上传图片时,对文件路径进行编码转换 `InputStream inputStream = ftp.retrieveFileStream(new String(filePath.getBytes("UTF-8"), "ISO-8859-1"));`,以避免因编码问题造成文件损坏[^2]。 ### 流处理问题 在文件下载过程中,流的读取和写入操作可能出现问题。要确保正确关闭输入输出流,防止数据丢失。以下是一个简单的Java下载图片的示例代码,展示了如何正确处理流: ```java import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; public class ImageDownloader { public static void main(String[] args) { String imageUrl = "https://example.com/image.jpg"; String savePath = "C:/local/path/image.jpg"; try { URL url = new URL(imageUrl); URLConnection connection = url.openConnection(); InputStream inputStream = connection.getInputStream(); FileOutputStream outputStream = new FileOutputStream(savePath); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } inputStream.close(); outputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } ``` ### 文件路径问题 在获取文件时,确保文件路径正确。如在Springboot实现文件下载时,使用 `ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX + "excelTemplate/template.xls");` 要保证文件确实存在于指定路径下,否则可能导致文件损坏或下载失败[^3]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值