Springboot uploads Tencent Cloud cos after realizing the temporary file dumped by the network image

Sometimes I copy a picture url and want to transfer it to my own Tencent Cloud cos for storage.

The implementation idea is: first save the network picture url to a temporary folder of the current project, then send Tencent Cloud cos object storage, return a url, and finally delete the temporary file picture.

Test Results

 1. util implementation class

package com.xxxx.util;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.UUID;

public class ImageUrlUtil {

    /**
     * 从网络url中下载文件图片
     */
    public static String downLoadByUrl(String imgUrl) throws IOException {
        URL url = new URL(imgUrl);
        //生成唯一的文件名
        String fileName = generateUniqueFileName();

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        //设置超时间为3秒
        conn.setConnectTimeout(5*1000);
        //防止屏蔽程序抓取而返回403错误
        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
        //conn.setRequestProperty("User-Agent", "Mozilla/5.0");
        //得到输入流
        InputStream inputStream = conn.getInputStream();
        //获取自己数组
        byte[] getData = readInputStream(inputStream);
        //获取项目根目录地址
        String propertiesFile = System.getProperty("user.dir")+ "/src/main/resources/static";
        //文件保存位置
        File saveDir = new File(propertiesFile);
        if(!saveDir.exists()) {
            saveDir.mkdir();
        }
        File file = new File(saveDir + File.separator + fileName);
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(getData);
        if(fos != null) {
            fos.close();
        }
        if(inputStream != null) {
            inputStream.close();
        }
        return propertiesFile + "/" + fileName;
    }

    /**
     * 从输入流中获取字节数组
     */
    public static byte[] readInputStream(InputStream inputStream) throws IOException {
        //创建一个Buffer字符串
        byte[] buffer = new byte[1024];
        //每次读取的字符串长度,如果为-1,代表全部读取完毕
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        //使用一个输入流从buffer里把数据读取出来
        while ((len = inputStream.read(buffer)) != -1) {
            //用输出流往buffer里写入数据,中间参数代表从哪个位置开始读,len代表读取的长度
            bos.write(buffer, 0, len);
        }
        //关闭输入流
        bos.close();
        //把outStream里的数据写入内存
        return bos.toByteArray();
    }

    /**
     * // 使用UUID生成一个唯一的文件名
     * @return
     */
    private static String generateUniqueFileName() {

        return UUID.randomUUID().toString() + ".jpg";
    }

    //删除临时文件
    public static Boolean deleteImage(String localFilePath) {
        File fileToDelete = new File(localFilePath);
        if(fileToDelete.exists()) {
            if(fileToDelete.delete()) {
                //本地临时文件删除成功
                return true;
            } else {
                //本地临时文件删除失败
                return false;
            }
        } else {
            //本地临时文件不存在
            return false;
        }
    }
}

2. Controller class

@GetMapping("/upload/image")
    public ApiRestResponse uploadImage(String url) {
        HashMap<String, Object> map = new HashMap();
        try {
            //得到一个保存在当前项目的临时文件
            String filePath = ImageUrlUtil.downLoadByUrl(url);
 
            File fileExists = new File(filePath);
            //判断源文件是否存在
            if (fileExists.exists()) {
                //上传到腾讯云 返回url
                String imageUrl = CosFileUtil.uploadImage(filePath);

                map.put("originalSrc", url);//源图片地址
                map.put("imageUrl", imageUrl);//腾讯云 图片地址
            } else {
                return ApiRestResponse.error(400, "图片上传失败~");
            }
            //删除临时文件
            ImageUrlUtil.deleteImage(filePath);

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return ApiRestResponse.success(map);
    }

Thank you for sharing the post:

Java downloads pictures from the network and saves them locally - Programmer Sought

Guess you like

Origin blog.csdn.net/deng_zhihao692817/article/details/131478875