繁体   English   中英

通过AJAX使用JavaScript从另一台服务器上传图像

[英]Upload image with JavaScript from another server via AJAX

我正在尝试(如果可能的话)使用AJAX请求通过JavaScript(允许使用jQuery)上传存储在另一个站点(而不是计算机上)上的图像。

假设我们有图片http://example.com/a.jpg 我需要提出AJAX请求,将此图像提交到http://test.com/process.php

  • 除了有效的上传文件之外,我无法编辑process.php文件来接受任何内容。
  • 浏览器支持并不重要。

这有可能吗? 由于安全问题,我们无法动态填充文件字段,因此也许这是无需用户选择文件即可发送文件的另一种方法。

我想我应该使用FormData ,不确定。

//正在接收文件。

var url  = "http://example.com/a.jpg"
var oReq = new XMLHttpRequest();

oReq.onload = function(e) {
    var blobData = oReq.response; // not responseText


    // Sending data.

    var formData = new FormData();


    // JavaScript file-like object
    var blob = new Blob([blobData], { type: "image/jpeg"});

    formData.append("webmasterfile", blob);

    var request = new XMLHttpRequest();
    request.open("POST", "http://test.com/process.php");
    request.send(formData);
}
oReq.open("GET", url, true);
oReq.responseType = "blob";
oReq.send();

资源:

https://developer.mozilla.org/en-US/docs/Web/API/FormData/append

https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects

https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest

假设example.com向用户显示了许多图像。

  • 用户点击图片
  • GET请求发送到服务器(包含“ image”参数)
  • 服务器向test.com发出POST请求

因此, 如果您使用PHP编写服务器代码,则您的代码应如下所示(或类似内容):

<?php

$image = $_GET['image']; // example.png
$file = dirname(__FILE__).$image; // /var/www/example/assets/img/example.png

$ch = curl_init();

$data = array('file' => $file);

curl_setopt($ch, CURLOPT_URL, 'http://test.com/process.php');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

curl_exec($ch);

?>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM