http - 如何使用 Lua 通过 multipart/form-data 发送文件?
问题描述
这是我的代码:
http = require("socket.http")
ltn12 = require("ltn12")
lfs = require "lfs"
respbody = {}
local _start = [[--abcd]]..'\r\n'..[[Content-Disposition: form-data; name="file"; filename="test.png"]]..'\r\n'..[[Content-Type: image/jpeg]]..'\r\n\r\n'
local _end = '\r\n'..[[--abcd--]]..'\r\n'
local file= io.open('./test.png')
local fileSize = lfs.attributes('./test.png').size
local body, code, headers, status = http.request {
method = "POST",
url = 'http://127.0.0.1:826/api/upload',
headers = {
["Content-Type"] = "multipart/form-data; boundary=abcd",
["Content-Length"] = fileSize + #_start + #_end
},
source = ltn12.source.cat(ltn12.source.string(_start),ltn12.source.file(file),ltn12.source.string(_end)),
sink = ltn12.sink.table(respbody)
}
print(body, code, headers, status, respbody)
我用这个演示来发送文件,但我不明白!这是结果:
解决方案
- 您需要以二进制模式读取文件
- 有一次我放弃了这个:
ltn12.source.file
并使用ltn12.source.string
, 由于文件长度不正确
试试我的解决方案,就像你的:
PS:您还需要确保在服务器端文件字段在客户端被命名为:basename ($_FILES ['file'] ['name']);
http = require("socket.http")
ltn12 = require("ltn12")
lfs = require "lfs"
http.TIMEOUT = 5
local function upload_file ( url, filename )
local fileHandle = io.open( filename,"rb")
if (fileHandle) then
local fileContent = fileHandle:read( "*a" )
fileHandle:close()
local boundary = 'abcd'
local header_b = 'Content-Disposition: form-data; name="file"; filename="' .. filename .. '"\r\nContent-Type: text/plain\r\n'
local fileContent = '--' ..boundary .. '\r\n' ..header_b ..'\r\n'.. fileContent .. '\r\n--' .. boundary ..'--\r\n'
local response_body = { }
local _, code = http.request {
url = url ,
method = "POST",
headers = { ["Content-Length"] = fileContent:len(),
['Content-Type'] = 'multipart/form-data; boundary=' .. boundary
},
source = ltn12.source.string(fileContent) ,
sink = ltn12.sink.table(response_body),
}
return code, table.concat(response_body)
else
return false, "File Not Found"
end
end
local rc,content = upload_file ('http://127.0.0.1:826/api/upload', 'test.png' )
print(rc,content)
推荐阅读
- .net - 无法从 EC2 实例元数据服务获取 IAM 安全凭证 - .Net
- reactjs - 排序时如何避免更改在react-table中展开的分组行的位置
- java - Maven 3.8.1 不支持 wrapperVersion,它必须至少为 4
- r - 如果 NA 在 BOTH 列中,则删除行
- java - Gradle Java Plugin 给出编译错误,但 Eclipse 中的相同代码工作正常
- java - 尝试在 Gitlab CI 管道上运行 Firestore 模拟器会出现“未安装 java”错误
- common-lisp - Common Lisp 将列表的成员从一个索引返回到另一个索引
- java - 电脑发送和手机发送的区别
- c# - 如何使用 System.Text.Json 将 Arraylist 项反序列化为具体类型?
- php - Laravel 护照与另一个要求冲突