如何在 cURL 中使用文件发送 json

我正在尝试在 Lua 中使用 cURL 发送 json 并附加多部分文件。已尝试以下方式,但不起作用:

local cURL = require "cURL"

c = cURL.easy{
  url        = "http://posttestserver.com/post.php",
  post       = true,
  httpheader = {
    "Content-Type: application/json";
  };
  postfields = "{}";
}

c:setopt_httppost(curl.form()
                 :add_file('file', recording_filename, 'audio/mp4',
                       filename..'.mp4', {'Content-length: ' .. fileSize}
             ))

c:perform()

任何帮助将不胜感激!谢谢!

点赞
用户1979882
用户1979882

这是错误的,在任何语言或库中上传文件时,必须每次使用multipart/form-data格式,而不是application/json。

对于您的情况,我建议您使用以下示例:

https://github.com/Lua-cURL/Lua-cURLv2/blob/master/examples/post.lua

local cURL = require("cURL")

c = cURL.easy_init()

c:setopt_url("http://localhost")
postdata = {
    --从文件系统中发布文件
   name = {file="post.lua",
       type="text/plain"},
   -- 从数据变量发布文件
   name2 = {file="dummy.html",
        data="<html><bold>bold</bold></html>",
        type="text/html"}}
c:post(postdata)
c:perform()

stream_postdata = {
   -- 从私有读取函数发布文件
   name = {file="stream.txt",
        stream_length="5",
        type="text/plain"}}

count = 0
c:post(stream_postdata)
c:perform({readfunction=function(n)
               if (count < 5)  then
                  count = 5
                  return "stream"
               end
               return nil
            end})
print("完成")
2017-03-03 10:24:20