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

时间:2017-03-03 10:08:33

标签: json curl post lua

我正在尝试使用Lua中的cURL发布json并附加multipart文件。尝试以下方式,但它不起作用:

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()

任何帮助都会非常值得注意!谢谢!

1 个答案:

答案 0 :(得分:1)

使用application/json发布文件不正确。每次在任何语言或库中发布文件时,您都必须使用multipart/form-data

对于您的情况,我将使用此示例:

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 = {  
   -- post file from filesystem
   name = {file="post.lua",
       type="text/plain"},
   -- post file from data variable
   name2 = {file="dummy.html",
        data="<html><bold>bold</bold></html>",
        type="text/html"}}
c:post(postdata)
c:perform()

stream_postdata = {
   -- post file from private read function
   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("Done")