我需要帮助将以下 Python 代码转换为 c# .net。此代码将文本文件发布/上传到网络服务器。Python 脚本已经过测试并且可以正常工作。我已经尝试了一些使用 HTTPClient 和 WebRequest 的解决方案,但没有成功。任何指导将不胜感激。
# request a session
client = requests.session()
# Establish the URL
newurl = 'https://localhost/filedist/upload/'
source_file = 'data/test.txt'
headers = {'Authorization': 'Token MYTOKEN'}
# Populate the values with our environment and target path
values = dict(environment='dev', path='Business/Tools')
files = dict(file=open(source_file, 'rb'))
r = client.post(newurl, files=files, data=values, headers=headers)
这是我的最新尝试,目前正在收到“禁止”错误。
public static async Task<string> UploadFile(string path, string fileName)
{
var client = new HttpClient();
string NewURL = "https://localhost/filedist/upload/";
string SourceFile = path;
var content = new MultipartFormDataContent();
client.DefaultRequestHeaders.Add("Authorization", "Token MYTOKEN");
Stream fs = System.IO.File.Open(path, FileMode.Open, FileAccess.Read, FileShare.None);
content.Add(CreateFileContent(fs, fileName, "text/plain"));
var parameters = new Dictionary<string, string> { { "environment", "dev" }, { "path", "Business/Tools" } };
content.Add(new FormUrlEncodedContent(parameters));
var response = await client.PostAsync(NewURL, content);
response.EnsureSuccessStatusCode();
if (response.IsSuccessStatusCode)
{
string responseString = response.Content.ReadAsStringAsync().Result;
return "true";
}
else
{
return "false";
}
}
private static StreamContent CreateFileContent(Stream stream, string fileName, string contentType)
{
try
{
var fileContent = new StreamContent(stream);
fileContent.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("form-data")
{
Name = "UploadedFile",
FileName = "\"" + fileName + "\""
};
开心每一天1111
相关分类