是否可以使用 createObjectURL 保存到文件夹中?

112*_*233 3 jquery

URL.createObjectURL(event.target.files[0] this makes me able to view the image just uploaded in the browser. Using the same hack is there a way, where I can store the file/image into a folder instead of URL?

 console.debug(URL.createObjectURL(event.target.files[0]));
Run Code Online (Sandbox Code Playgroud)

上面的日志出来了,这个:blob:http%3A//mysite.localhost.com/f96c26b4-9938-4f6e-941e-edbdae3454c9

我只是想知道是否可以替换mysite.localhost.com为文件夹路径。我什至尝试将 URL 替换为文件夹的完整路径,但createObjectURL仅适用于URL. 有没有将文件保存到文件夹的功能?

Kai*_*ido 8

根据你的评论

我想保存在服务器端..

答案变成“是的,这是可能的”。

首先我们来解释一下你的误解:

方法返回的字符串URL.createObjectURL()是一个 URI,指向浏览器内存中的某个位置,作为第一个参数传递的 Blob 将作为文件进行访问。

除了通过此 URI 之外,无法访问此文件,并且此 URI 仅适用于当前会话。您无法共享它,也无法从其他计算机访问它,甚至无法使用其他浏览器从同一台计算机访问它。当调用它的文档关闭时它将被删除(在某些实现中,它需要硬刷新)。


但你实际上需要的是保存你传递的Blob。
借助对象,这可以很容易地实现FormData,它允许您通过 XHR 请求发送它。

input.onchange = function() {

  var formData = new FormData();
  formData.append('file', this.files[0], 'yourFileName.ext');

  var xhr = new XMLHttpRequest();
  xhr.onload = callback; // assuming you've got a callback function
  xhr.open('POST', yourServerSideFileHandlerScript);
  xhr.send(formData);

};
Run Code Online (Sandbox Code Playgroud)

或者使用 jQuery,

$(input).on('change', function() {

  var formData = new FormData();
  formData.append('file', this.files[0], 'yourFileName.ext');

  $.ajax({
    url: yourServerSideFileHandlerScript,
    data: formData,
    processData: false,
    contentType: false,
    type: 'POST',
    success: callback
  });

});
Run Code Online (Sandbox Code Playgroud)

然后,您将能够在上传任何文件时在服务器端获取它。

服务器端代码示例(此处为 php):

if ( isset( $_FILES["file"] ) ){
  $dir = 'some/dir/';
  $blob = file_get_contents($_FILES["file"]['tmp_name']);
  file_put_contents($dir.$_FILES["file"]["name"], $blob);
}
Run Code Online (Sandbox Code Playgroud)