向OpenAI API上传Rust文件遇415错误,寻求解决方法
问题:OpenAI文件上传返回415 Unsupported Media Type错误
我想开发一个工具让ChatGPT为Rust文件生成文档,但OpenAI API消息长度有限,打算通过上传文件提供上下文。用reqwest写的上传代码返回「Failed to upload file. Status code: 415 Unsupported Media Type」错误,改Content-Type为text/plain也没用,代码如下:
use std::fmt::Write; use std::fs; use std::io; use std::io::Read; use chatgpt::prelude::*; use clap::Parser; use syn; use syn::Item; use reqwest; #[derive(Parser, Debug)] #[command(author, version, about, long_about = None)] struct Args { /// Path to the source code to document #[arg(short, long)] file_path: String, } fn main() { let args = Args::parse(); let mut file = std::fs::File::open(args.file_path).unwrap(); let mut content = String::new(); file.read_to_string(&mut content).unwrap(); let ast = syn::parse_file(&content).unwrap(); let mut input_buffer = String::new(); // Getting the API key here let key = "My key that I have replaced for obvious reasons"; { // Create a reqwest client let client = reqwest::blocking::Client::new(); // Make a POST request to the OpenAI API let response = client .post("https://api.openai.com/v1/files") .header("Authorization", "Bearer My key that I have replaced for obvious reasons") .header("Content-Type", "application/json") .body(content.clone()) .send().unwrap(); // Check if the request was successful if response.status().is_success() { println!("File uploaded successfully!"); } else { println!("Failed to upload file. Status code: {}", response.status()); } std::mem::forget(client); std::mem::forget(response); } }
错误原因及修正方案
核心问题
OpenAI的/v1/files接口要求用multipart/form-data格式提交请求,而非直接传递文本内容或JSON。该接口必须包含两个字段:
file:要上传的文件(需包含文件名和内容)purpose:文件用途,比如"assistants"(用于助手上下文)或"fine-tune"(用于微调)
代码修正步骤
- 移除手动设置的
Content-Typeheader,reqwest会自动为multipart请求生成正确的Content-Type - 使用
reqwest::blocking::multipart::Form构建请求体,添加file和purpose字段 - 无需调用
std::mem::forget,reqwest的Client和Response会自动处理内存释放
修正后的代码
use std::fs; use clap::Parser; use reqwest::blocking::multipart; #[derive(Parser, Debug)] #[command(author, version, about, long_about = None)] struct Args { /// Path to the source code to document #[arg(short, long)] file_path: String, } fn main() -> Result<(), Box<dyn std::error::Error>> { let args = Args::parse(); let api_key = "Your actual OpenAI API key here"; // 读取文件内容 let file_content = fs::read_to_string(&args.file_path)?; // 构建multipart表单 let form = multipart::Form::new() // 添加文件字段:文件名从路径获取,内容为读取的文本 .file("file", &args.file_path)? // 设置文件用途,这里用assistants作为示例 .text("purpose", "assistants"); let client = reqwest::blocking::Client::new(); let response = client .post("https://api.openai.com/v1/files") .header("Authorization", format!("Bearer {}", api_key)) .multipart(form) .send()?; if response.status().is_success() { let response_json = response.json::<serde_json::Value>()?; println!("文件上传成功!文件ID: {}", response_json["id"]); } else { let error_msg = response.text()?; eprintln!("文件上传失败,状态码: {},错误信息: {}", response.status(), error_msg); } Ok(()) }
额外说明
- 需要在
Cargo.toml中添加serde_json依赖(用于解析响应) - 确保API密钥正确,且账户有足够权限上传文件
- 文件大小不能超过OpenAI的限制(当前最大为512MB)
内容的提问来源于stack exchange,提问作者Makogan
相关产品推荐
相关产品推荐

