【问题标题】:save static image same way like uploaded image像上传图片一样保存静态图片
【发布时间】:2016-04-24 14:50:12
【问题描述】:

我正在使用 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 文件进行保存。

【问题讨论】:

    标签: javascript php jquery image upload


    【解决方案1】:

    您可以使用XMLHttpRequest,将responseType 设置为"blob"new File() 构造函数可用于 chrome / chromium 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>

    【讨论】:

    猜你喜欢
    • 2017-07-23
    • 1970-01-01
    • 2021-02-22
    • 2018-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-10
    相关资源
    最近更新 更多