package org.springblade.api.utils;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.nio.file.Files;
import java.nio.file.Path;

public class FileUtils {

	public static File getFileByUrl(String fileUrl, String suffix){
		try {
			// 从URL获取文件内容
			URL url = new URL(fileUrl);
			URLConnection urlConnection = url.openConnection();
			// 创建一个临时文件
			File tempFile = File.createTempFile("tempfile", suffix);
			try (InputStream inputStream = new BufferedInputStream(urlConnection.getInputStream());
				 OutputStream outputStream = Files.newOutputStream(tempFile.toPath())) {

				// 复制文件内容到临时文件
				byte[] buffer = new byte[4096];
				int bytesRead;
				while ((bytesRead = inputStream.read(buffer)) != -1) {
					outputStream.write(buffer, 0, bytesRead);
				}
				return tempFile;
			}

		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static void main(String[] args) {
		System.out.println(getFileByUrl("https://ai.my-123.cn/pic/product-line/upload/20240415/b3df69006e3de829970490d181870ddf.jpg", "jpg"));
	}
}
