本文整理汇总了C#中System.Net.Http.MultipartFormDataContent.Add方法的典型用法代码示例。如果您正苦于以下问题:C# MultipartFormDataContent.Add方法的具体用法?C# MultipartFormDataContent.Add怎么用?C# MultipartFormDataContent.Add使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Net.Http.MultipartFormDataContent
的用法示例。
在下文中一共展示了MultipartFormDataContent.Add方法的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: Create
public async Task<ActionResult> Create(Area area, HttpPostedFileBase upload)
{
try
{
area.Id = Guid.NewGuid();
var formData = new MultipartFormDataContent();
var json = JsonConvert.SerializeObject(area);
formData.Add(new StringContent(json, Encoding.Unicode, "application/json"));
if (upload != null && upload.ContentLength > 0)
{
formData.Add(new StreamContent(upload.InputStream), upload.FileName, upload.FileName);
}
var response = await saguClient.PostAsync("api/areas", formData);
if (response.IsSuccessStatusCode)
{
return RedirectToAction("Index");
}
else
return Content("An error occurred, status code " + response.ReasonPhrase);
}
catch
{
return Content("An error occurred.");
}
}
示例3: 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);
}
}
示例4: 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");
}
}
示例5: 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;
}
}
示例6: 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;
}
示例7: 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;
}
示例8: SendAddressesToApi
public string SendAddressesToApi(string csvPath)
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(CensusBatchGeoCodeUri);
var content = new MultipartFormDataContent();
var fileContent = new ByteArrayContent(System.IO.File.ReadAllBytes("addresses.csv"));
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
Name = "addressFile",
FileName = "addresses.csv"
};
fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
content.Add(fileContent);
// Not a FormUrlEncodedContent class due to an ostensible bug in census API that
// rejects key/value formatting and requires 'benchmark' in a 'name' field
var benchMarkContent = new StringContent("9");
benchMarkContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
Name = "benchmark"
};
content.Add(benchMarkContent);
var result = client.PostAsync("", content).Result;
string resultContent = result.Content.ReadAsStringAsync().Result;
return resultContent;
}
}
示例9: UploadImageBinaryRequest
/// <exception cref="ArgumentNullException"></exception>
internal HttpRequestMessage UploadImageBinaryRequest(string url, byte[] image, string album = null,
string title = null, string description = null)
{
if (string.IsNullOrEmpty(url))
throw new ArgumentNullException(nameof(url));
if (image == null)
throw new ArgumentNullException(nameof(image));
var request = new HttpRequestMessage(HttpMethod.Post, url);
var content = new MultipartFormDataContent($"{DateTime.UtcNow.Ticks}")
{
{new StringContent("file"), "type"},
{new ByteArrayContent(image), nameof(image)}
};
if (album != null)
content.Add(new StringContent(album), nameof(album));
if (title != null)
content.Add(new StringContent(title), nameof(title));
if (description != null)
content.Add(new StringContent(description), nameof(description));
request.Content = content;
return request;
}
示例10: BuildMessage
protected override HttpRequestMessage BuildMessage(IRestRequest request)
{
// Create message content
var content = new MultipartFormDataContent();
foreach (var param in request.Parameters) {
var file = param.Value as FileParameter;
if (file != null) {
var contentPart = new ByteArrayContent(file.Content);
contentPart.Headers.Add("Content-Type", file.ContentType);
content.Add(contentPart, param.Key, file.Name);
}
else {
var contentPart = new StringContent(param.Value.ToString());
content.Add(contentPart, param.Key);
}
}
// Build message
var message = new HttpRequestMessage(request.Verb.ToHttpMethod(), request.Command) {
Content = content
};
return message;
}
示例11: Send
protected override void Send(ITask currentTask, string text, FileInfo logFile)
{
var mailSubject = text.Substring(0, text.IndexOf("\r\n"));
var form = new MultipartFormDataContent();
form.Add(new StringContent(options.From), "from");
foreach (var to in options.To)
{
form.Add(new StringContent(to), "to");
}
form.Add(new StringContent(mailSubject), "subject");
form.Add(new StringContent(text), "text");
if (logFile != null && logFile.Exists)
{
form.Add(new StreamContent(logFile.OpenRead()), "attachment", logFile.Name);
}
var credentials = new NetworkCredential("api", options.MailgunApiKey);
var handler = new HttpClientHandler { Credentials = credentials };
using (var httpClient = new HttpClient(handler))
{
httpClient.BaseAddress = new Uri(options.MailgunBaseUrl + options.MailgunDomain + "/");
var response = httpClient.PostAsync("messages", form).Result;
response.EnsureSuccessStatusCode();
}
}
示例12: SendImageSet
private static void SendImageSet(ImageSet imageSet)
{
var multipartContent = new MultipartFormDataContent();
var imageSetJson = JsonConvert.SerializeObject(imageSet,
new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
});
multipartContent.Add(new StringContent(imageSetJson, Encoding.UTF8, "application/json"), "imageset");
int counter = 0;
foreach (var image in imageSet.Images)
{
var imageContent = new ByteArrayContent(image.ImageData);
imageContent.Headers.ContentType = new MediaTypeHeaderValue(image.MimeType);
multipartContent.Add(imageContent, "image" + counter++, image.FileName);
}
var response = new HttpClient()
.PostAsync("http://localhost:53908/api/send", multipartContent)
.Result;
var responseContent = response.Content.ReadAsStringAsync().Result;
Trace.Write(responseContent);
}
示例13: 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);
}
}
}
}
示例14: GetStreamValidation
public void GetStreamValidation()
{
Stream stream0 = null;
Stream stream1 = null;
try
{
MultipartFormDataContent content = new MultipartFormDataContent();
content.Add(new StringContent("Not a file"), "notafile");
content.Add(new StringContent("This is a file"), "file", "filename");
MultipartFileStreamProvider instance = new MultipartFileStreamProvider(Path.GetTempPath());
stream0 = instance.GetStream(content.ElementAt(0).Headers);
Assert.IsType<FileStream>(stream0);
stream1 = instance.GetStream(content.ElementAt(1).Headers);
Assert.IsType<FileStream>(stream1);
Assert.Equal(2, instance.BodyPartFileNames.Count);
Assert.Contains("BodyPart", instance.BodyPartFileNames[0]);
Assert.Contains("BodyPart", instance.BodyPartFileNames[1]);
}
finally
{
if (stream0 != null)
{
stream0.Close();
}
if (stream1 != null)
{
stream1.Close();
}
}
}
示例15: UploadImgur
public static async Task<ImgurEntity> UploadImgur(IRandomAccessStream fileStream)
{
try
{
var imageData = new byte[fileStream.Size];
for (int i = 0; i < imageData.Length; i++)
{
imageData[i] = (byte)fileStream.AsStreamForRead().ReadByte();
}
var theAuthClient = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Post, "https://api.imgur.com/3/image");
request.Headers.Authorization = new AuthenticationHeaderValue("Client-ID", "e5c018ac1f4c157");
var form = new MultipartFormDataContent();
var t = new StreamContent(fileStream.AsStream());
// TODO: See if this is the correct way to use imgur's v3 api. I can't see why we would still need to convert images to base64.
string base64Img = Convert.ToBase64String(imageData);
t.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
form.Add(new StringContent(base64Img), @"image");
form.Add(new StringContent("file"), "type");
request.Content = form;
HttpResponseMessage response = await theAuthClient.SendAsync(request);
string responseString = await response.Content.ReadAsStringAsync();
if (responseString == null) return null;
var imgurEntity = JsonConvert.DeserializeObject<ImgurEntity>(responseString);
return imgurEntity;
}
catch (WebException)
{
}
catch (IOException)
{
return null;
}
return null;
}