Java文件上传功能实现 - 使用OpenAI API
好的,我将使用GPT-3.5 Turbo模型为您回答问题,并为您提供一个Java编写的文件上传功能示例代码:
import java.io.File;
import java.io.IOException;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class FileUploader {
private static final String API_ENDPOINT = 'https://api.openai.com/v1/files';
private static final String API_KEY = 'YOUR_API_KEY'; // 替换为您的OpenAI API密钥
public static void main(String[] args) {
File file = new File('path/to/file.txt'); // 替换为要上传的文件路径
try {
String fileUrl = uploadFile(file);
System.out.println('文件上传成功!URL:' + fileUrl);
} catch (IOException e) {
System.err.println('文件上传失败:' + e.getMessage());
}
}
private static String uploadFile(File file) throws IOException {
OkHttpClient client = new OkHttpClient();
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart('file', file.getName(),
RequestBody.create(MediaType.parse('application/octet-stream'), file))
.build();
Request request = new Request.Builder()
.url(API_ENDPOINT)
.header('Authorization', 'Bearer ' + API_KEY)
.post(requestBody)
.build();
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) {
throw new IOException('上传文件失败,响应码: ' + response.code());
}
String responseBody = response.body().string();
// 解析响应体以获取文件URL
// 示例响应格式:{"object": "file", "id": "file-abc123", "created": 1677649420, "filename": "file.txt", "url": "https://api.openai.com/v1/files/file-abc123"}
return parseFileUrl(responseBody);
}
}
private static String parseFileUrl(String responseBody) {
// 根据实际响应格式解析文件URL
// 这里仅作示范,您可能需要根据实际情况自行实现
// 示例使用简单的正则表达式提取URL
String regex = '"url":\s*"([^"]+)"';
java.util.regex.Pattern pattern = java.util.regex.Pattern.compile(regex);
java.util.regex.Matcher matcher = pattern.matcher(responseBody);
if (matcher.find()) {
return matcher.group(1);
}
return null;
}
}
请注意,上述代码需要您替换API_KEY和file路径,API_KEY为您的OpenAI API密钥,file为要上传的文件路径。此示例使用OkHttp库来执行HTTP请求并通过OpenAI API上传文件。请确保在运行代码之前安装OkHttp库。
希望这可以满足您的需求!如果您有任何进一步的问题,请随时提问。
原文地址: https://www.cveoy.top/t/topic/bPB9 著作权归作者所有。请勿转载和采集!