postman Azure Function MultipartContent

uqdfh47h  于 2023-10-18  发布在  Postman
关注(0)|答案(1)|浏览(146)

我有一个问题,如何从Azure函数的多部分响应接收数据
我有一个同时下载数据+ N个文件内容的案例。
作为响应,我得到了JSON数据+

{
    "headers": [
        {
            "key": "Content-Type",
            "value": [
                "application/octet-stream"
            ]
        },
        {
            "key": "Content-Disposition",
            "value": [
                "form-data; name=\"files\"; filename=\"file\""
            ]
        }
    ]
},

但我没办法下载
我的代码

MultipartContent content = new MultipartContent("mixed", "----Boundary");
                content.Add(JsonContent.Create(result, new MediaTypeHeaderValue("application/json")));

                foreach (var result1 in result)
                {
                    foreach (var room in result1.Rooms)
                    {
                        var plan = room.// Something

                        WebClient webClient = new WebClient();
                        var filedata = await webClient.DownloadDataTaskAsync(new Uri(plan .FileUrl));

                        MemoryStream stream = new MemoryStream();
                        stream.Write(filedata, 0, filedata.Length);

                        var fileContent = new StreamContent(stream);
                        fileContent.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/octet-stream");
                        fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
                        {
                            Name = "\"files\"",
                            FileName = "\"" + plan.FileName + "\""
                        };
                        content.Add(fileContent);
                    }
                }
                
                 return new OkObjectResult(content);

有变通办法吗?也许我不明白什么

unhi4e5o

unhi4e5o1#

  • 我尝试了这个多部分内容的替代方案,它对我和json和二进制输出有效:-*
    我的函数.cs:-
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;

public class YourData
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
    public string Description { get; set; }
}

public static class Function1
{
    [FunctionName("DownloadFiles")]
    public static async Task<IActionResult> Run(
        [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
        ILogger log)
    {
        // Replace this with your data retrieval logic
        List<YourData> result = GetDataFromSource();

        // Convert JSON data to a string
        string jsonData = JsonConvert.SerializeObject(result);

        // Convert JSON string to bytes
        byte[] jsonBytes = Encoding.UTF8.GetBytes(jsonData);

        // Create a binary data (sample binary content)
        byte[] binaryData = new byte[] { 0x41, 0x42, 0x43, 0x44, 0x45 }; // Example: ABCDE

        // Create a response object
        var response = req.HttpContext.Response;

        // Set response headers before sending any content
        response.Headers.Add("Content-Type", "multipart/mixed; boundary=----Boundary");

        // Create a multipart content
        var multipartContent = new MultipartContent("mixed", "----Boundary");

        // Add JSON data as a string to the multipart content
        var jsonContent = new ByteArrayContent(jsonBytes);
        jsonContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
        multipartContent.Add(jsonContent);

        // Add binary data to the multipart content
        var binaryContent = new ByteArrayContent(binaryData);
        binaryContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
        multipartContent.Add(binaryContent);

        // Write the multipart content to the response body
        await multipartContent.CopyToAsync(response.Body);

        return new OkResult();
    }

    // Replace with your data retrieval logic
    private static List<YourData> GetDataFromSource()
    {
        // Implement logic to retrieve your data
        return new List<YourData>
        {
            new YourData
            {
                Id = 1,
                Name = "SampleName1",
                Price = 10.0m,
                Description = "Sample description 1"
            },
            new YourData
            {
                Id = 2,
                Name = "SampleName2",
                Price = 20.0m,
                Description = "Sample description 2"
            }
            // Add more data items as needed
        };
    }
}

输出:-

具有多部分内容逻辑:-

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;

public class YourData
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
    public string Description { get; set; }
}

public static class Function1
{
    [FunctionName("DownloadFiles")]
    public static async Task<IActionResult> Run(
        [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
        ILogger log)
    {
        // Replace this with your data retrieval logic
        List<YourData> result = GetDataFromSource();

        // Convert JSON data to a string
        string jsonData = JsonConvert.SerializeObject(result);

        // Create a binary data (sample binary content)
        byte[] binaryData = Encoding.UTF8.GetBytes(jsonData); // Assuming you want to download JSON as text

        // Create a response object
        var response = req.HttpContext.Response;

        // Set response headers before sending any content
        response.Headers.Add("Content-Type", "multipart/mixed; boundary=----Boundary");

        // Create a multipart content
        var multipartContent = new MultipartContent("mixed", "----Boundary");

        // Add JSON data as a string to the multipart content
        var jsonContent = new ByteArrayContent(Encoding.UTF8.GetBytes(jsonData));
        jsonContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
        multipartContent.Add(jsonContent);

        // Add binary data to the multipart content
        var binaryContent = new ByteArrayContent(binaryData);
        binaryContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
        binaryContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
        {
            Name = "files",
            FileName = "sample.json" // Specify the appropriate file name with extension
        };
        multipartContent.Add(binaryContent);

        // Write the multipart content to the response body
        await multipartContent.CopyToAsync(response.Body);

        return new OkResult();
    }

    // Replace with your data retrieval logic
    private static List<YourData> GetDataFromSource()
    {
        // Implement logic to retrieve your data
        return new List<YourData>
        {
            new YourData
            {
                Id = 1,
                Name = "SampleName1",
                Price = 10.0m,
                Description = "Sample description 1"
            },
            new YourData
            {
                Id = 2,
                Name = "SampleName2",
                Price = 20.0m,
                Description = "Sample description 2"
            }
            
        };
    }
}

输出:-

相关问题