Reputation: 73
I have created Function App for uploading multiple files on FTP server. I have received all files using req.Form.Files
. but When I get the request. I actually found my file from HttpClient
request in req.Body
. When I upload file from Postman in Body->FormData it, works fine but now I need to send post request with file by code.
I had tried below code with reference of Sending a Post using HttpClient and the Server is seeing an empty Json file this link.
HttpContent content = new StreamContent (stream);
content.Headers.ContentType = new MediaTypeHeaderValue("multipart/form-data");
HttpResponseMessage response = client.PostAsync ("url", content).Result;
But I want file in req.Form.Files
. Where user might have uploaded multiple files or one file.
Note : For now I have a file which is being generated by code. But it should not be saved on local so I'm trying to send stream. in HttpContent
Upvotes: -1
Views: 794
Reputation: 1506
Below are the steps for Post Async using function app
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req, ILogger log)
{
string Connection = Environment.GetEnvironmentVariable("AzureWebJobsStorage");
string containerName = Environment.GetEnvironmentVariable("ContainerName");
var file = req.Form.Files["File"];**
var filecontent = file.OpenReadStream();
var blobClient = new BlobContainerClient(Connection, containerName);
var blob = blobClient.GetBlobClient(file.FileName);
byte[] byteArray = Encoding.UTF8.GetBytes(filecontent.ToString());
File details while using req.Form.Files
Successfully uploaded a text file to blob storage.
Edit:
Here is the Post request Using HttpClient
var file = @"C:\Users\...\Documents\test.txt";
await using var stream = System.IO.File.OpenRead(file);
using var request = new HttpRequestMessage(HttpMethod.Post, "file");
using var content = new MultipartFormDataContent
{
{ new StreamContent(stream),"File", "test.txt" }
};
request.Content = content;
await client.SendAsync(request);
return new OkObjectResult("File uploaded successfully");
Upvotes: 2