本文整理汇总了C#中System.Net.Http.MultipartFormDataContent类的典型用法代码示例。如果您正苦于以下问题:C# MultipartFormDataContent类的具体用法?C# MultipartFormDataContent怎么用?C# MultipartFormDataContent使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
MultipartFormDataContent类属于System.Net.Http命名空间,在下文中一共展示了MultipartFormDataContent类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: sendPost
public void sendPost()
{
// Définition des variables qui seront envoyés
HttpContent stringContent1 = new StringContent(param1String); // Le contenu du paramètre P1
HttpContent stringContent2 = new StringContent(param2String); // Le contenu du paramètre P2
HttpContent fileStreamContent = new StreamContent(paramFileStream);
//HttpContent bytesContent = new ByteArrayContent(paramFileBytes);
using (var client = new HttpClient())
using (var formData = new MultipartFormDataContent())
{
formData.Add(stringContent1, "P1"); // Le paramètre P1 aura la valeur contenue dans param1String
formData.Add(stringContent2, "P2"); // Le parmaètre P2 aura la valeur contenue dans param2String
formData.Add(fileStreamContent, "FICHIER", "RETURN.xml");
// formData.Add(bytesContent, "file2", "file2");
try
{
var response = client.PostAsync(actionUrl, formData).Result;
MessageBox.Show(response.ToString());
if (!response.IsSuccessStatusCode)
{
MessageBox.Show("Erreur de réponse");
}
}
catch (Exception Error)
{
MessageBox.Show(Error.Message);
}
finally
{
client.CancelPendingRequests();
}
}
}
示例2: File
public async Task<Models.Media> File(Stream fileStream, string name = "", string description = "", string projectId = null)
{
using (var formData = new MultipartFormDataContent())
{
AddStringContent(formData, _client.Authentication.FieldName, _client.Authentication.Value);
AddStringContent(formData, "project_id", projectId);
AddStringContent(formData, "name", name);
AddStringContent(formData, "description", description);
// Add the file stream
var fileContent = new StreamContent(fileStream);
fileContent.Headers.Add("Content-Type", "application/octet-stream");
fileContent.Headers.Add("Content-Disposition", "form-data; name=\"file\"; filename=\"" + name + "\"");
formData.Add(fileContent, "file", name);
// HttpClient problem workaround
var boundaryValue = formData.Headers.ContentType.Parameters.FirstOrDefault(p => p.Name == "boundary");
if (boundaryValue != null)
{
boundaryValue.Value = boundaryValue.Value.Replace("\"", string.Empty);
}
// Upload the file
var response = await _client.Post(Client.UploadUrl, formData);
return _client.Hydrate<Models.Media>(response);
}
}
示例3: upload_image
static async void upload_image(string path)
{
Console.WriteLine("Uploading {0}", path);
try {
using (var client = new HttpClient()) {
using (var stream = File.OpenRead(path)) {
var content = new MultipartFormDataContent();
var file_content = new ByteArrayContent(new StreamContent(stream).ReadAsByteArrayAsync().Result);
file_content.Headers.ContentType = new MediaTypeHeaderValue("image/png");
file_content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "screenshot.png",
Name = "foo",
};
content.Add(file_content);
client.BaseAddress = new Uri("https://pajlada.se/poe/imgup/");
var response = await client.PostAsync("upload.php", content);
response.EnsureSuccessStatusCode();
Console.WriteLine("Done");
}
}
} catch (Exception) {
Console.WriteLine("Something went wrong while uploading the image");
}
}
示例4: Upload
public Stream Upload(string url, string filename, Stream fileStream)
{
HttpContent stringContent = new StringContent(filename);
HttpContent fileStreamContent = new StreamContent(fileStream);
using (var handler = new ProgressMessageHandler())
using (var client = HttpClientFactory.Create(handler))
using (var formData = new MultipartFormDataContent())
{
client.Timeout = new TimeSpan(1, 0, 0); // 1 hour should be enough probably
formData.Add(fileStreamContent, "file", filename);
handler.HttpSendProgress += (s, e) =>
{
float prog = (float)e.BytesTransferred / (float)fileStream.Length;
prog = prog > 1 ? 1 : prog;
if (FileProgress != null)
FileProgress(filename, prog);
};
var response_raw = client.PostAsync(url, formData);
var response = response_raw.Result;
if (!response.IsSuccessStatusCode)
{
return null;
}
return response.Content.ReadAsStreamAsync().Result;
}
}
示例5: Should_Accept_Only_Text_Content
public void Should_Accept_Only_Text_Content()
{
// Arrange
Mock<IStorageRepository> storageRepositoryMock;
Mock<IFileProcessor> fileProcessorMock;
Mock<IChecksumCalculator> checksumCalculatorMock;
Mock<IMetadataRepository> metadataRepositoryMock;
var controller = this.ConfigureController(out storageRepositoryMock, out fileProcessorMock, out checksumCalculatorMock, out metadataRepositoryMock);
var multipartContent = new MultipartFormDataContent();
var binaryContent = Enumerable.Repeat(Enumerable.Range(14, 255).ToArray(), 20).SelectMany(x => x.Select(y => y)).Select(x=>(byte)x).ToArray();
var fileContent = new ByteArrayContent(binaryContent);
fileContent.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment") { FileName = "Test.txt" };
fileContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("something/that_we_dont_expect");
multipartContent.Add(fileContent);
controller.Request.Content = multipartContent;
// Act
Task<IHttpActionResult> task = controller.Post();
task.Wait();
// Assert
GenericValueResult<List<MetadataInfo>> result = task.Result as GenericValueResult<List<MetadataInfo>>;
result.Should().NotBeNull("Wrong data type was returned from the controller");
var t = result.Value as IEnumerable<Models.MetadataInfo>;
t.Should().NotBeNull("Wrong data type was returned as a result of controller's work");
var informationFromService = t.First();
informationFromService.Id.Should().NotHaveValue();
informationFromService.ProcessingResult.Should().Be(UploadController.ContentTypeCannotBeAcceptedMessage);
}
示例6: UploadFileToJira
private static async Task UploadFileToJira(string file)
{
var url = IssueUrl(file);
var response = await client.GetStringAsync(url);
dynamic issue = JObject.Parse(response);
var info = GetIssueInfo(file);
foreach (var attachment in issue.fields.attachment)
{
if (attachment.filename != info.OriginalFilename)
continue;
if (!options.Overwrite)
{
Console.WriteLine($"{issue.key} already contains '{info.OriginalFilename}' skipping...");
return;
}
Console.WriteLine($"{issue.key} Replacing existing attachment '{info.OriginalFilename}'");
await client.DeleteAsync(attachment.self.ToString());
}
Console.WriteLine($"{issue.key} uploading '{info.OriginalFilename}'");
var form = new MultipartFormDataContent
{
{ new StreamContent(File.OpenRead(file)), "\"file\"", info.OriginalFilename }
};
await client.PostAsync(IssueUrl(file) + "/attachments", form);
}
示例7: Main
static void Main(string[] args)
{
var message = new HttpRequestMessage();
var content = new MultipartFormDataContent();
var files = new List<string> {"WebApiDoc01.png", "WebApiDoc02.png"};
foreach (var file in files)
{
var filestream = new FileStream(file, FileMode.Open);
var fileName = System.IO.Path.GetFileName(file);
content.Add(new StreamContent(filestream), "file", fileName);
}
message.Method = HttpMethod.Post;
message.Content = content;
message.RequestUri = new Uri("http://localhost:8081/api/test/filesNoContentType");
var client = new HttpClient();
client.SendAsync(message).ContinueWith(task =>
{
if (task.Result.IsSuccessStatusCode)
{
var result = task.Result;
Console.WriteLine(result);
}
});
Console.ReadLine();
}
示例8: send
/// <summary>
/// Assincronouslly send the fields in the list to webServer in url parameter
/// NextStep: add a percentage of uploaded data!
/// </summary>
/// <param name="fields"></param>
/// <param name="url"></param>
/// <returns></returns>
internal static async Task<string> send(List<field> fields, string url)
{
HttpClient httpClient = new HttpClient();
MultipartFormDataContent form = new MultipartFormDataContent();
foreach(field f in fields)
{
if(f.kind == fieldKind.text)
{
form.Add(new StringContent(f.content), f.name);
}
else if (f.kind == fieldKind.file)
{
HttpContent content = new ByteArrayContent(f.bytes);
content.Headers.Add("Content-Type", f.contentType);
form.Add(content, f.name, f.fileName);
}
}
HttpResponseMessage response = await httpClient.PostAsync(url, form);
response.EnsureSuccessStatusCode();
httpClient.Dispose();
return response.Content.ReadAsStringAsync().Result;
}
示例9: SendMessageWithImageAsync
private async static Task<bool> SendMessageWithImageAsync(string message, string chatId, string messageId,
Stream imageStream)
{
var tghttpClient = new HttpClient();
imageStream.Seek(0, SeekOrigin.Begin);
var buf = ReadFully(imageStream);
var imageContent = new ByteArrayContent(buf);
imageContent.Headers.ContentType = MediaTypeHeaderValue.Parse("image/png");
// Send Message, as well as image
var endpointUrl =
new Uri(string.Format(RequestTemplate.RpcOpUrl, RequestTemplate.AppId, "sendPhoto"));
var content = new MultipartFormDataContent();
/*content.Add(new FormUrlEncodedContent(new List<KeyValuePair<string,string>>
{
new KeyValuePair<string, string>("chat_id", chatId),
new KeyValuePair<string, string>("reply_to_message_id", messageId),
new KeyValuePair<string, string>("caption", message)
}));*/
content.Add(imageContent, "photo", string.Format("{0}.png", Guid.NewGuid()));
content.Add(new ByteArrayContent(Encoding.UTF8.GetBytes(chatId)),"chat_id");
content.Add(new ByteArrayContent(Encoding.UTF8.GetBytes(messageId)), "reply_to_message_id");
content.Add(new ByteArrayContent(Encoding.UTF8.GetBytes(message)), "aptiond");
var result = await
tghttpClient.PostAsync(endpointUrl, content);
var content2 = await result.Content.ReadAsStringAsync();
return result.IsSuccessStatusCode;
}
示例10: AttachFiles
private void AttachFiles(IMail message, MultipartFormDataContent content)
{
var files = FetchFileBodies(message);
foreach (var file in files)
{
var ifile = file.Value;
var fileContent = new StreamContent(ifile.OpenAsync(FileAccess.Read).Result);
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
Name = "files[" + ifile.Name + "]",
FileName = ifile.Name
};
fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/octet-stream");
content.Add(fileContent);
}
var streamingFiles = FetchStreamingFileBodies(message);
foreach (KeyValuePair<string, MemoryStream> file in streamingFiles) {
var name = file.Key;
var stream = file.Value;
var fileContent = new StreamContent(stream);
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
Name = "files[" + name + "]",
FileName = name
};
fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/octet-stream");
content.Add(fileContent);
}
}
示例11: Upload
private static async Task<HttpStatusCode> Upload()
{
var files = new List<string>();
files.Add(@"c:\temp\midi.xml");
files.Add(@"c:\temp\maxi.xml");
files.Add(@"c:\temp\efti.xml");
var apiUri = string.Format("https://api-dev.qbranch.se/api/customers/{0}/tickets/{1}/attachments",
customerId, ticketId);
var message = new HttpRequestMessage();
message.RequestUri = new Uri(apiUri);
message.Headers.Add("qnet-api-key", apiKey);
message.Method = HttpMethod.Post;
var content = new MultipartFormDataContent();
foreach (var file in files)
{
var filestream = new FileStream(file, FileMode.Open);
var fileName = Path.GetFileName(file);
content.Add(new StreamContent(filestream), "file", fileName);
}
message.Content = content;
using (var client = new HttpClient())
{
var response = await client.SendAsync(message);
return response.StatusCode;
}
}
示例12: Sign
public static RequestResponse Sign(byte[] document, string phone, string code)
{
using (var client = new HttpClient())
{
using (var content =
new MultipartFormDataContent("Upload----" + DateTime.Now))
{
content.Add(new StringContent("pdf"), "type");
content.Add(new StringContent(phone), "phone");
content.Add(new StringContent(code), "code");
content.Add(new StringContent("true"), "timestamp");
content.Add(new StringContent("Vardas Pavardenis"), "pdf[contact]");
content.Add(new StringContent("Test"), "pdf[reason]");
content.Add(new StringContent("Vilnius"), "pdf[location]");
content.Add(new StringContent("test.pdf"), "pdf[files][0][name]");
content.Add(new StringContent(Convert.ToBase64String(document)), "pdf[files][0][content]");
content.Add(
new StringContent(
BitConverter.ToString(SHA1.Create().ComputeHash(document)).Replace("-", "").ToLower()),
"pdf[files][0][digest]");
using (
var message =
client.PostAsync("https://developers.isign.io/mobile/sign.json?access_token=" + Api.accessToken,
content))
{
var input = message.Result;
var serializator = new DataContractJsonSerializer(typeof(RequestResponse));
return (RequestResponse)serializator.ReadObject(input.Content.ReadAsStreamAsync().Result);
}
}
}
}
示例13: GetPackagesStatus
public static void GetPackagesStatus()
{
var client = new HttpClient();
List<Package> _packages = Databases.serverModel.PackageSet.Where(x => x.Labeled == true && x.Package_id == null).ToList();
foreach (Package p in _packages)
{
MediaLogBarcodePackage package = new MediaLogBarcodePackage();
package.user = "87";
package.package = new MediaLogBarcodePack { package_id = p.Temporary_package_id };
string json = JsonConvert.SerializeObject(package);
MultipartFormDataContent form = new MultipartFormDataContent();
StringContent cont = new StringContent(json);
form.Add(new StringContent(json), "pack");
HttpResponseMessage response = client.PostAsync("http://csomagteszt.media-log.hu/packages/get_status", form).Result;
response.EnsureSuccessStatusCode();
string sd = response.Content.ReadAsStringAsync().Result;//164058, 000000000009
if (sd.StartsWith("OK"))
{
p.Status = sd.Remove(0, 4);
Databases.serverModel.SaveChanges();
}
else
{
//gáz van
}
}
}
示例14: GetCaptchaStr
public string GetCaptchaStr(byte[] imagefile)
{
try
{
//var result = httpClient.GetAsync("http://poster.de-captcher.com/").Result;
//result.Dispose();
MultipartFormDataContent content = new MultipartFormDataContent();
var values = new[]
{
new KeyValuePair<string, string>("function", "picture2"),
new KeyValuePair<string, string>("username", username),
new KeyValuePair<string, string>("password", password),
new KeyValuePair<string, string>("pict_type", "0"),
new KeyValuePair<string, string>("submit", "Send"),
};
foreach (var keyValuePair in values)
{
content.Add(new StringContent(keyValuePair.Value),
String.Format("\"{0}\"", keyValuePair.Key));
}
content.Add(new StreamContent(new MemoryStream(imagefile)), "pict");
var result = httpClient.PostAsync("http://poster.de-captcher.com/", content).Result;
string strContent = result.Content.ReadAsStringAsync().Result;
major = strContent.Split('|')[1];
min = strContent.Split('|')[2];
return strContent.Split('|')[5];
}
catch
{
return "";
}
}
示例15: GetBalance
public string GetBalance()
{
try
{
MultipartFormDataContent content = new MultipartFormDataContent();
var values = new[]
{
new KeyValuePair<string, string>("function", "balance"),
new KeyValuePair<string, string>("username", username),
new KeyValuePair<string, string>("password", password),
new KeyValuePair<string, string>("submit", "Send"),
};
foreach (var keyValuePair in values)
{
content.Add(new StringContent(keyValuePair.Value),
String.Format("\"{0}\"", keyValuePair.Key));
}
var result = httpClient.PostAsync("http://poster.de-captcher.com/", content).Result;
return result.Content.ReadAsStringAsync().Result;
}
catch
{
return "";
}
}