Flutter multipart request along name value pair to server - dart

I have to send to multipart request to server along with name value pair to server i mean id along with it. Can you please help me how to send id along with multipart files.
Upload() async {
var stream = new https.ByteStream(DelegatingStream.typed(Files[0].openRead()));
var length = await Files[0].length();
var stream1 = new https.ByteStream(DelegatingStream.typed(Files[1].openRead()));
var length1 = await Files[1].length();
var stream2 = new https.ByteStream(DelegatingStream.typed(Files[2].openRead()));
var length2 = await Files[2].length();
var uri = Uri.parse(openurl);
var request = new https.MultipartRequest("POST", uri);
var multipartFile1 = new https.MultipartFile('XX', stream, length,
filename: basename(Files[0].path));
var multipartFile2 = new https.MultipartFile('YY', stream1, length1,
filename: basename(Files[0].path));
var multipartFile3 = new https.MultipartFile('ZZ', stream2, length2,
filename: basename(Files[0].path));
//contentType: new MediaType('image', 'png'));
request.files.add(multipartFile1);
request.files.add(multipartFile2);
request.files.add(multipartFile3);
request.fields.addAll(other)
var response = await request.send();
print(response.statusCode);
response.stream.transform(utf8.decoder).listen((value) {
print(value);
});
}
Thanks in advance
Sathish

I just had a problem similar to this. I had to upload an image along a key-value pair. I realize that I could upload the key-value pair using request.fields:
var request = new http.MultipartRequest("POST", uri);
request.fields['description'] = 'description';
request.fields['File-Name'] = 'FILENAME.jpg';
request.fields['qr_size'] = '3';

Related

No response received to multipart/mixed HTTP request

I am trying to use the Dynamics 365 Web API to GET records. The fetch query generated is too long to use a normal GET query so a workaround is to POST the request instead.
I have simplifed the fetch statement here for ease.
Ignore the lack of async/await and use of .Result, that can easily be sorted afterwards.
Code:
var clientcred = new ClientCredential(Config.ClientId, Config.ClientSecret);
var authenticationContext = new AuthenticationContext($"{Config.AadInstance}{Config.TenantId}");
var authenticationResult = authenticationContext.AcquireTokenAsync(Config.DynamicsUrl, clientcred).Result;
var token = authenticationResult.AccessToken;
var client = new HttpClient();
client.BaseAddress = new Uri("https://foobar.crm4.dynamics.com");
client.Timeout = new TimeSpan(0, 2, 0);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("OData-Version", "4.0");
client.DefaultRequestHeaders.Add("OData-MaxVersion", "4.0");
client.DefaultRequestHeaders.Add("Prefer", "odata.include-annotations=\"*\"");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
var req = new HttpRequestMessage(System.Net.Http.HttpMethod.Post, $"/api/data/v9.1/$batch");
var content = "--batch_rob--\n" +
"Content-Type: application/http\n" +
"Content-Transfer-Encoding: binary\n" +
$"GET {Config.BaseUrl}contacts?fetchXml=<fetch count=\"10\" ><entity name=\"contact\" ><attribute name=\"fullname\" /></entity></fetch> HTTP/1.1\n" +
"OData-Version: 4.0\n" +
"OData-MaxVersion: 4.0\n" +
"--batch_rob--";
using (var content2 = new MultipartContent())
{
content2.Add(new StringContent(content));
content2.Headers.Remove("Content-Type");
content2.Headers.TryAddWithoutValidation("Content-Type", "multipart/mixed;boundary=batch_rob");
var request = new HttpRequestMessage(System.Net.Http.HttpMethod.Post, $"/api/data/v9.1/$batch")
{
Content = content2
};
var response = client.SendAsync(request).Result;
var outcome2 = response.Content.ReadAsStringAsync().Result;
}
This all compiles and appears to run fine. The response however does not contain the JSON I expect (the result of the GET query) but rather is just:
--batchresponse_20851dc6-4ff6-4914-a749-66f451985f67--
Any idea what I have missed?
This is based on the example demonstrated here:
https://dreamingincrm.com/2017/01/15/executing-large-fetchxml-with-webapi/

Google App Script error 404: Response not defined

My code is supposed to get some data from google sheet and POST to a system via external API.I, however, keep running into the error 404 when I run the code.
On debug, it indicates that response is not defined. Here is the potion of the code with the issue. Am I missing something?
function postLeave(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
// used getLastRow() function [1] to narrow the array to have only cells with data.
var range = sheet.getRange("K2:K"+sheet.getLastRow()).getValues();
var searchString = "";
for (var i = 0; i<range.length; i++) {
if(range[i][0] == searchString) {
var lastRow = sheet.getRange(2+i,1,1,10).getValues();
var userid = sheet.getRange("I2:I" + sheet.getLastRow()).getValues();
var data = {
//'user_id': lastRow[0][8],
"leave_type_id":lastRow[0][9],
"date":lastRow[0][7],
"hours":lastRow[0][6],
};
var payload = JSON.stringify(data);
var options = {
'method': 'POST',
'Content-Type': 'application/json',
'payload' : data,
};
var url = 'https://api.10000ft.com/api/v1/users/' + userid + '/time_entries?auth=key;
var response = UrlFetchApp.fetch(url).getContentText();
if (response === 200) {
//var json = JSON.parse(response);
sheet.getRange(2+i, 11).setValue(1);
}
else {
sheet.getRange(2+i, 11).setValue(0);
Logger.log(response)
}
}
}
}
Documentation
Challenge with endpoints.
https://github.com/10Kft/10kft-api/blob/master/sections/assignables.md
https://github.com/10Kft/10kft-api/blob/master/sections/leave-types.md
https://github.com/10Kft/10kft-api/blob/master/sections/time-entries.md
How about this modification?
Modification points:
Content-Type cannot be directly used to the option of UrlFetchApp.fetch().
var payload = JSON.stringify(data); is not used.
options is not used at var response = UrlFetchApp.fetch(url).getContentText();. In this case, it requests to the URL with the GET method.
var url = 'https://api.10000ft.com/api/v1/users/' + userid + '/time_entries?auth=key; is not enclosed by '.
Unfortunately, from the official document, I couldn't understand if it is required to send this data in json data or form data. So I proposed following 2 patterns. Please check them.
Modified script 1:
In this modified script, the data is sent as json data. Please set each variables. And also please set key.
From:
var payload = JSON.stringify(data);
var options = {
'method': 'POST',
'Content-Type': 'application/json',
'payload' : data,
};
var url = 'https://api.10000ft.com/api/v1/users/' + userid + '/time_entries?auth=key;
var response = UrlFetchApp.fetch(url).getContentText();
To:
var payload = JSON.stringify(data);
var options = {
'method': 'POST',
'contentType': 'application/json',
'payload' : payload,
};
var key = "###"; // <--- Please set your key.
var url = 'https://api.10000ft.com/api/v1/users/' + userid + '/time_entries?auth=' + encodeURIComponent(key);
var response = UrlFetchApp.fetch(url, options).getContentText();
Modified script 2:
In this modified script, the data is sent as form data. Please set each variables. And also please set key.
From:
var payload = JSON.stringify(data);
var options = {
'method': 'POST',
'Content-Type': 'application/json',
'payload' : data,
};
var url = 'https://api.10000ft.com/api/v1/users/' + userid + '/time_entries?auth=key;
var response = UrlFetchApp.fetch(url).getContentText();
To:
var options = {
'method': 'POST',
'payload' : data,
};
var key = "###"; // <--- Please set your key.
var url = 'https://api.10000ft.com/api/v1/users/' + userid + '/time_entries?auth=' + encodeURIComponent(key);
var response = UrlFetchApp.fetch(url, options).getContentText();
Note:
In above modified scripts, it supposes that each value in data object and key are correct.
Reference:
Class UrlFetchApp

Why do my web api receive null values when posting to web API?

My Web API is receiving null value in Httpclient PostAsJsonAsync:
public static async Task<DefaultApiResponse<T>> PostList<T>(string url, string token, List<AddEventViewModel.Agenda> request)
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", token);
var content = JsonConvert.SerializeObject(request);
var buffer = System.Text.Encoding.UTF8.GetBytes(content);
var byteContent = new ByteArrayContent(buffer);
byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var httpResponse = await client.PostAsJsonAsync(url, byteContent);
var defaultresponse = JsonConvert.DeserializeObject<DefaultApiResponse<T>>(await httpResponse.Content.ReadAsStringAsync());
return defaultresponse;
}
Why?
I would try posting as a StringContent object instead
var content = new StringContent(
JsonConvert.SerializeObject(request),
Encoding.UTF8,
"application/json");
defaultresponse = await client.PostAsync(url, content);

Send HTTP Post with .Net Core

how can I set up an HTTP call in asp.net core mvc
$url = "https://prod-25.northeurope.logic.azure.com:443/..."
$parms = #{
Uri = $url
Method = 'post'
ContentType = 'application/json'
body = '{"recipient": "stefan.","body":"Test"}'
}
curl #parms
using
using System.Net.Http;
and your code will be
var url = "http://yoursite.com/Home/Insert";
var data = new {"recipient"= "stefan.", "body"="Test"};
using(var client = new HttpClient())
{
var response = await client.PostAsJsonAsync(url, data);
string responseContent = await response.Content.ReadAsStringAsync(); // only to see response as text ( debug perpose )
var result = await ProcessedResult<TResult>(response); // cast it to TResult or any type that you expect to retrieve
}

How to upload a small file plus metadata with GraphServiceClient to OneDrive with a single POST request?

I would like to upload small files with metadata (DriveItem) attached so that the LastModifiedDateTime property is set properly.
First, my current workaround is this:
var graphFileSystemInfo = new Microsoft.Graph.FileSystemInfo()
{
CreatedDateTime = fileSystemInfo.CreationTimeUtc,
LastAccessedDateTime = fileSystemInfo.LastAccessTimeUtc,
LastModifiedDateTime = fileSystemInfo.LastWriteTimeUtc
};
using (var stream = new System.IO.File.OpenRead(localPath))
{
if (fileSystemInfo.Length <= 4 * 1024 * 1024) // file.Length <= 4 MB
{
var driveItem = new DriveItem()
{
File = new File(),
FileSystemInfo = graphFileSystemInfo,
Name = Path.GetFileName(item.Path)
};
try
{
var newDriveItem = await graphClient.Me.Drive.Root.ItemWithPath(item.Path).Content.Request().PutAsync<DriveItem>(stream);
await graphClient.Me.Drive.Items[newDriveItem.Id].Request().UpdateAsync(driveItem);
}
catch (Exception ex)
{
throw;
}
}
else
{
// large file upload
}
}
This code works by first uploading the content via PutAsync and then updating the metadata via UpdateAsync. I tried to do it vice versa (as suggested here) but then I get the error that no file without content can be created. If I then add content to the DriveItem.Content property, the next error is that the stream's ReadTimeout and WriteTimeout properties cannot be read. With a wrapper class for the FileStream, I can overcome this but then I get the next error: A stream property 'content' has a value in the payload. In OData, stream property must not have a value, it must only use property annotations.
By googling, I found that there is another way to upload data, called multipart upload (link). With this description I tried to use the GraphServiceClient to create such a request. But it seems that this is only fully implemented for OneNote items. I took this code as template and created the following function to mimic the OneNote behavior:
public static async Task UploadSmallFile(GraphServiceClient graphClient, DriveItem driveItem, Stream stream)
{
var jsondata = JsonConvert.SerializeObject(driveItem);
// Create the metadata part.
StringContent stringContent = new StringContent(jsondata, Encoding.UTF8, "application/json");
stringContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("related");
stringContent.Headers.ContentDisposition.Name = "Metadata";
stringContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
// Create the data part.
var streamContent = new StreamContent(stream);
streamContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("related");
streamContent.Headers.ContentDisposition.Name = "Data";
streamContent.Headers.ContentType = new MediaTypeHeaderValue("text/plain");
// Put the multiparts together
string boundary = "MultiPartBoundary32541";
MultipartContent multiPartContent = new MultipartContent("related", boundary);
multiPartContent.Add(stringContent);
multiPartContent.Add(streamContent);
var requestUrl = graphClient.Me.Drive.Items["F4C4DC6C33B9D421!103"].Children.Request().RequestUrl;
// Create the request message and add the content.
HttpRequestMessage hrm = new HttpRequestMessage(HttpMethod.Post, requestUrl);
hrm.Content = multiPartContent;
// Send the request and get the response.
var response = await graphClient.HttpProvider.SendAsync(hrm);
}
With this code, I get the error Entity only allows writes with a JSON Content-Type header.
What am I doing wrong?
Not sure why the provided error occurs, your example appears to be a valid and corresponds to Request body example
But the alternative option could be considered for this matter, since Microsoft Graph supports JSON batching, the folowing example demonstrates how to upload a file and update its metadata within a single request:
POST https://graph.microsoft.com/v1.0/$batch
Accept: application/json
Content-Type: application/json
{
"requests": [
{
"id":"1",
"method":"PUT",
"url":"/me/drive/root:/Sample.docx:/content",
"headers":{
"Content-Type":"application/octet-stream"
},
},
{
"id":"2",
"method":"PATCH",
"url":"/me/drive/root:/Sample.docx:",
"headers":{
"Content-Type":"application/json; charset=utf-8"
},
"body":{
"fileSystemInfo":{
"lastModifiedDateTime":"2019-08-09T00:49:37.7758742+03:00"
}
},
"dependsOn":["1"]
}
]
}
Here is a C# example
var bytes = System.IO.File.ReadAllBytes(path);
var stream = new MemoryStream(bytes);
var batchRequest = new BatchRequest();
//1.1 construct upload file query
var uploadRequest = graphClient.Me
.Drive
.Root
.ItemWithPath(System.IO.Path.GetFileName(path))
.Content
.Request();
batchRequest.AddQuery(uploadRequest, HttpMethod.Put, new StreamContent(stream));
//1.2 construct update driveItem query
var updateRequest = graphClient.Me
.Drive
.Root
.ItemWithPath(System.IO.Path.GetFileName(path))
.Request();
var driveItem = new DriveItem()
{
FileSystemInfo = new FileSystemInfo()
{
LastModifiedDateTime = DateTimeOffset.UtcNow.AddDays(-1)
}
};
var jsonPayload = new StringContent(graphClient.HttpProvider.Serializer.SerializeObject(driveItem), Encoding.UTF8, "application/json");
batchRequest.AddQuery(updateRequest, new HttpMethod("PATCH"), jsonPayload, true, typeof(Microsoft.Graph.DriveItem));
//2. execute Batch request
var result = await graphClient.SendBatchAsync(batchRequest);
var updatedDriveItem = result[1] as DriveItem;
Console.WriteLine(updatedDriveItem.LastModifiedDateTime);
where SendBatchAsync is an extension method which implements JSON Batching support for Microsoft Graph .NET Client Library

Resources