使用MultipartFormData发送的参数值错误

时间:2019-02-14 13:28:49

标签: ios swift alamofire multipart

我所做的只是像这样:

using System;
using System.Collections.Generic;
using System.Text;
using Npgsql;
using NpgsqlTypes;

class Model
{
    public int value1 { get; }
    public int value2 { get; }

    public Model(int value1, int value2)
    {
        this.value1 = value1;
        this.value2 = value2;
    }
}

class Program
{
    static void Main(string[] args)
    {
        var dataRows = new List<Model>();
        dataRows.Add(new Model(3,2));
        dataRows.Add(new Model(27,-10));
        dataRows.Add(new Model(11,-11));

        var connString = "Host=127.0.0.1;Port=5432;Username=postgres;Database=dbtest1";

        // tabletest1
        // ----------
        //   id        SERIAL PRIMARY KEY
        // , value1    INT NOT NULL
        // , value2    INT NOT NULL

        using (var conn = new NpgsqlConnection(connString))
        {
            conn.Open();

            var cmd = new NpgsqlCommand();
            cmd.Connection = conn;
            cmd.CommandText = $"INSERT INTO tabletest1 (value1,value2) VALUES (@value1,@value2)";
            var parameterValue1 = cmd.Parameters.Add("value1", NpgsqlDbType.Integer);
            var parameterValue2 = cmd.Parameters.Add("value2", NpgsqlDbType.Integer);
            cmd.Prepare();

            var batchCommand = new StringBuilder();

            foreach (var d in dataRows)
            {
                parameterValue1.Value = d.value1;
                parameterValue2.Value = d.value2;
                batchCommand.Append(cmd.CommandText);
                batchCommand.Append(";");
            }
            Console.WriteLine(batchCommand.ToString());
            // conn.ExecuteNonQuery(batchCommand.ToString());
        }
    }
}

这是我通过多部分发送到服务而看到的:

enter image description here

您可能会发现这是错误的。它应该看起来像这样:

    func postMultipart(_ url: URL, parameters: [String: Any]?, headers: [String: String]?, image: UIImage?, success: @escaping SuccessHandler, failure: @escaping ErrorHandler) {
        manager.upload(multipartFormData: { multipart in
            if let image = image, let data = UIImagePNGRepresentation(image) {
                multipart.append(data, withName: "Passport", fileName: "picture.png", mimeType: "image/png")
            }
            if let parameters = parameters {
                for (key, value) in parameters {
                    multipart.append(self.archiver.data(from: value), withName: key)
                }
            }
        }, to: url, method: .post, headers: headers) { result in
            //parse result here
        }
    }

为什么它不是字符串,而是一些存档器对象?

1 个答案:

答案 0 :(得分:0)

您可能会需要

for (key, value) in parameters {
   multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key)
}