Http 通过多部分请求上载文件
我需要上传一个zip文件到一个url,该url接受在多部分请求中传递的文件。“多部分/表单数据”请求中要绑定到的部分的名称为“存档” 到目前为止,我所拥有的:Http 通过多部分请求上载文件,http,d,Http,D,我需要上传一个zip文件到一个url,该url接受在多部分请求中传递的文件。“多部分/表单数据”请求中要绑定到的部分的名称为“存档” 到目前为止,我所拥有的: auto f = new BufferedFile(<path_to_file>, FileMode.In); scope (exit) f.close(); http = HTTP(<post_url>); http.addRequestHeade
auto f = new BufferedFile(<path_to_file>, FileMode.In);
scope (exit) f.close();
http = HTTP(<post_url>);
http.addRequestHeader("Content-Type", "multipart/form-data;boundary=heregoes");
http.verifyPeer(false);
http.method = HTTP.Method.post;
http.onSend = (void[] data){
return f.read(cast(ubyte[]) data);
};
http.contentLength = cast(size_t) f.size;
http.setCookieJar("<cookie_file_used_for_auth>");
http.perform();
auto f=new BufferedFile(,FileMode.In);
范围(退出)f.关闭();
http=http();
addRequestHeader(“内容类型”,“多部分/表单数据;边界=heregoes”);
http.verifyPeer(false);
http.method=http.method.post;
http.onSend=(void[]数据){
返回f.read(cast(ubyte[])数据;
};
http.contentLength=cast(size\u t)f.size;
http.setCookieJar(“”);
http.perform();
如何在请求中设置要将文件映射到的密钥“archive”
谢谢我不太使用std.net.curl,因此我不知道是否有更简单的方法,但您发送的数据只是线路上的一个斑点,因此您可以手动设置其他值 不要只发送数据,把它放在MIME信封中。不久前,我写了这个小类来帮助形成:
/// Creates a multipart/form-data object that is suitable for file uploads and other kinds of POST
class FormData {
struct MimePart {
string name;
const(void)[] data;
string contentType;
string filename;
}
MimePart[] parts;
void append(string key, in void[] value, string contentType = null, string filename = null) {
parts ~= MimePart(key, value, contentType, filename);
}
private string boundary = "0016e64be86203dd36047610926a"; // FIXME
ubyte[] toBytes() {
string data;
foreach(part; parts) {
data ~= "--" ~ boundary ~ "\r\n";
data ~= "Content-Disposition: form-data; name=\""~part.name~"\"";
if(part.filename !is null)
data ~= "; filename=\""~part.filename~"\"";
data ~= "\r\n";
if(part.contentType !is null)
data ~= "Content-Type: " ~ part.contentType ~ "\r\n";
data ~= "\r\n";
data ~= cast(string) part.data;
data ~= "\r\n";
}
data ~= "--" ~ boundary ~ "--\r\n";
return cast(ubyte[]) data;
}
}
我知道代码很糟糕,最近我还没有测试过它,但输出的眼球是正确的。它应该是这样工作的:
auto data = new FormData();
data.append("archive", "YOUR DATA", "application/octet-stream"); // or whatever mime type you need
auto bytes = data.toBytes();
然后,当curl请求时,发送字节而不是文件内容。HTTP
的setPostData
方法看起来像是放置它的地方。请记住,在set post data中将您的内容类型也设置为具有边界的多部分/表单数据(如果愿意,您可以在我的类中更改)
我知道curl库也有函数可以为您完成这项工作。。。但是我不认为高级std.net.curl界面会暴露它们:(非常感谢。但是我不得不在这里对它进行一些修改:“数据~=”内容配置:表单数据,“->”数据~=”内容配置:表单数据.酷,修好了。还有其他办法吗?我希望有一个更简单的方法,但如果可行,我们至少有一些解决方案!