从服务器到服务器的http传输文件

2021-12-24 00:00:00 file-upload php html

使用 html 表单,我们可以使用 enctype="multipart/form-data" 将文件从客户端上传到服务器,输入 type="file" 等等在.

with html forms we can upload a file from a client to a server with enctype="multipart/form-data", input type="file" and so on.

有没有办法让一个文件已经在服务器上,然后以同样的方式将它传输到另一台服务器?

Is there a way to have a file already ON the server and transfer it to another server the same way?

感谢提示.

//哇!这是我见过最快的问答页面!!

// WoW! This is the fastest question answering page i have ever seen!!

推荐答案

当浏览器将文件上传到服务器时,它会发送一个包含文件内容的 HTTP POST 请求.

When the browser is uploading a file to the server, it sends an HTTP POST request, that contains the file's content.

你必须复制它.


对于 PHP,最简单的(或者至少是最常用的) 解决方案可能是使用 curl.


With PHP, the simplest (or, at least, most used) solution is probably to work with curl.

如果您查看可以使用 curl_setopt,你会看到这个:CURLOPT_POSTFIELDS (引用):

If you take a look at the list of options you can set with curl_setopt, you'll see this one : CURLOPT_POSTFIELDS (quoting) :

要在 HTTPPOST"中发布的完整数据手术.
要发布文件,在文件名前面加上@ 并使用完整路径.
这可以是作为 urlencoded 字符串传递,如'para1=val1&para2=val2&...' 或作为以字段名称为键的数组和字段数据作为值.
如果值是一个数组,Content-Type 标头将设置为 multipart/form-data.

The full data to post in a HTTP "POST" operation.
To post a file, prepend a filename with @ and use the full path.
This can either be passed as a urlencoded string like 'para1=val1&para2=val2&...' or as an array with the field name as key and field data as value.
If value is an array, the Content-Type header will be set to multipart/form-data.


未经测试,但我认为这样的事情应该可以解决问题 - 或者至少
帮助您入门:


Not tested,but I suppose that something like this should do the trick -- or at least
help you get started :

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/your-destination-script.php");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
        'file' => '@/..../file.jpg',
         // you'll have to change the name, here, I suppose
         // some other fields ?
));
$result = curl_exec($ch);
curl_close($ch);

基本上,你:

  • 正在使用 curl
  • 必须设置目标网址
  • 表示你希望curl_exec返回结果,而不是输出它
  • 正在使用 POST,而不是 GET
  • 正在发布一些数据,包括一个文件 -- 请注意文件路径前的 @.
  • are using curl
  • have to set the destination URL
  • indicate you want curl_exec to return the result, and not output it
  • are using POST, and not GET
  • are posting some data, including a file -- note the @ before the file's path.

相关文章