保存静态图像的方式与上传的图像相同


save static image same way like uploaded image

我正在用JavaScript开发一组工具,我在保存静态图像时遇到了麻烦。首先,我创建了上传器来上传稍后保存在目录中的图像upload/这些图像。

上传的图像(文件)将像这样发送到服务器:

$.ajax({
        data: { file: e.dataTransfer.file },
        url: 'server/uploading_files.php',
        method: 'POST',
        success: function (response) {
           ....
       }
});

我很想对我只有路径的图像做同样的事情 ->静态保存它们。
问题出在我发送到服务器端的结构中。因为e.dataTransfer.file看起来像这样:

FileList{0: File, length: 1}
   0: File
      lastModified:1441797733000
      lastModifiedDate:Wed Sep 09 2015 13:22:13 GMT+0200 (CEST)
      name:"sp_dom1.jpg"
      size:563989
      type:"image/jpeg"
      webkitRelativePath:""

当我想保存静态图像时,我只有没有任何结构的路径。

有没有解决方案如何构建相同的结构来上传静态图像?我不想使用 2 个不同的.php文件进行保存。

您可以使用

XMLHttpRequestresponseType设置为 "blob"new File()构造函数可在铬/铬 38+

var dfd = new $.Deferred();
var pathToImage = "http://lorempixel.com/50/50/";
var request = new XMLHttpRequest();
request.responseType = "blob";
request.open("GET", pathToImage);
request.onload = function() {
  var file = this.response;
  dfd.resolve(
    new File([file]
             , file.name 
               || "img-" + new Date().getTime() 
                  + "." + file.type.split("/")[1]
             , {
                 type: file.type
               }
    )
  )
};
request.send();
dfd.then(function(data) {
  // do stuff with `data`
  // i.e.g.;
  // $.ajax({
  //      data: { file: data },
  //      url: 'server/uploading_files.php',
  //      method: 'POST',
  //      success: function (response) {
  //         ....
  //     }
  // });
  console.log(data);
  var img = new Image;
  img.onload = function() {
    $("body").append(this)
  }
  img.src = URL.createObjectURL(data);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>