//·写入文件··filename可能需要根据你的接口接收参数名称修改const string filePartHeader = "Content-Disposition: form-data; name= "[0! ":filename= "[1} rin”+model-token: "CD630C964E4CD4949677D3D71049D1BA"rn”+"Content-Type: application/octet-stream'r n'r'n”://var header=string.Format (filePartHeader, fileKeylame, filePath) :var header= string.Format(filePartHeader,"file",filePath):var headerbytes = Encoding.UTF8.GetBytes (header): 把代码打印http请求信息
时间: 2024-02-21 13:58:45 浏览: 67
以下是将文件上传的完整代码,并添加了打印请求信息的功能:
```csharp
public static async Task<string> UploadFile(string url, string filePath)
{
const string fileKeyName = "file";
const string filePartHeader = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n" + "model-token: \"CD630C964E4CD4949677D3D71049D1BA\"\r\n" + "Content-Type: application/octet-stream\r\n\r\n";
string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
var content = new StreamContent(fileStream);
content.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
Name = fileKeyName,
FileName = Path.GetFileName(filePath)
};
content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
var client = new HttpClient();
client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 Edge/16.16299");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip"));
using (var formData = new MultipartFormDataContent(boundary))
{
var header = string.Format(filePartHeader, fileKeyName, Path.GetFileName(filePath));
var headerBytes = Encoding.UTF8.GetBytes(header);
formData.Add(content);
var request = new HttpRequestMessage(HttpMethod.Post, url);
request.Content = formData;
request.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 Edge/16.16299");
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
request.Headers.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip"));
request.Headers.TryAddWithoutValidation("Content-Type", $"multipart/form-data; boundary={boundary}");
Console.WriteLine(request.ToString());
Console.WriteLine(Encoding.UTF8.GetString(headerBytes));
var response = await client.SendAsync(request);
return await response.Content.ReadAsStringAsync();
}
}
```
函数中,使用 HttpRequestMessage 类创建了一个 HTTP 请求对象,并设置了请求头部分和请求体。然后使用 HttpClient 类发送请求,并打印了请求信息和请求头部分。函数返回上传结果。
阅读全文