在cURL中更改上传文件的名称? [英] Change name of upload file in cURL?

查看:310
本文介绍了在cURL中更改上传文件的名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用cURL上传文件。因为cURL需要文件的完整路径,所以这里是我的代码:

I want to upload a file using cURL. Since cURL requires full path to the file so here is my code:

curl_setopt($ch, CURLOPT_POSTFIELDS, array("submit" => "submit", "file" => "@path/to/file.ext"));
curl_exec($ch);


$ b < b
$ b

However cURL will also post this full path of the file in the request header:


Content-Disposition:form-data; name =file; filename =/ path / to / file.ext

Content-Disposition: form-data; name="file"; filename="/path/to/file.ext"

但我想要的只是


Content-Disposition:form-data; name =file; filename =file.ext

Content-Disposition: form-data; name="file"; filename="file.ext"

所以我将代码更改为

curl_setopt($ch, CURLOPT_POSTFIELDS, array("submit" => "submit", "file" => "@file.ext"));
chdir("path/to"); # change current working directory to where the file is placed
curl_exec($ch);
chdir("path"); # change current working directory back

然后cURL只是抛出一个错误信息

And then cURL simply throws an error message


无法打开文件file.ext

couldn't open file "file.ext"

推荐答案

新方法(自PHP 5.5开始) href =http://php.net/curlfile =nofollow> CURLFile :

New method (since PHP 5.5) using CURLFile:

$file = new CURLFile('path/to/file.ext');
$file->setPostFilename('file.ext');

使用它几乎相同:

"file" => $file

旧方法

而不是

"file" => "@path/to/file.ext"

你可以告诉cURL使用另一个文件名: p>

you can tell cURL to use another filename:

"file" => "@path/to/file.ext; filename=file.ext"

path / to / file.ext 作为文件源,但 file.ext 为filename。

That way it will use path/to/file.ext as file source, but file.ext as filename.

你需要一个非常绝对的路径,所以你可能缺少一个领先的 / / path /to/file.ext 。因为你使用PHP,总是做一个 realpath()

You'll need a very absolute path though, so you're probably missing a leading /: /path/to/file.ext. Since you're using PHP, always do a realpath():

"file" => '@' . realpath($pathToFile) . '; filename=' . basename($pathToFile);

或类似的东西。

这篇关于在cURL中更改上传文件的名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆