使用JS从localStorage上传文件

时间:2017-10-16 20:03:42

标签: javascript

我正在尝试从URL下载文件,然后将其存储在localStorage中,然后将其发布到终点。

<script>
        var xhr = new XMLHttpRequest();

        xhr.open('GET',
            'https://maxcdn.icons8.com/Share/icon/Logos//google_logo1600.png',
            true);
        xhr.responseType = "blob";
        xhr.onload = function(e){ //Stringify blob...
            //reload the icon from storage
            var fr = new FileReader();
            fr.onload =
                function(e) {
                    localStorage['icon'] = e.target.result;
                   sendFile();
                };
            fr.readAsDataURL(xhr.response);
        };
        xhr.send(null);


        function sendFile(){
            var form = document.createElement('form');
            form.setAttribute('method', 'post');
            form.setAttribute('action', 'http://posttestserver.com/post.php');
            form.setAttribute('enctype', 'multipart/form-data');

            var payload = {'uploadfield': localStorage['icon']};

            var hiddenField = document.createElement("input");
            hiddenField.setAttribute("type", "file");
            hiddenField.setAttribute("name", 'uploadfield');
            hiddenField.setAttribute("value", payload.uploadfield);
            form.appendChild(hiddenField);

            document.body.appendChild(form);
            form.submit();
        }
    </script>

我是这样做的。但似乎文件没有上传/发布。有没有更好的方法呢?基本上,我试图在页面加载时下载文件,然后将文件发布到端点。

1 个答案:

答案 0 :(得分:0)

你的做法存在一个缺陷 您无法设置值为file的任何输入类型的值(从空值""开始清除输入字段)

如果它可行,你肯定不会将值设置为base64字符串,它必须是File对象

以下是一些跟踪问题:

https://github.com/w3c/FileAPI/issues/19
https://github.com/w3c/FileAPI/issues/24

现在要解决此问题,您必须提交FormData并使用Ajax

这是es5版本:

&#13;
&#13;
fetch('https://maxcdn.icons8.com/Share/icon/Logos//google_logo1600.png')
.then(function(res){
  return res.blob()
})
.then(sendfile)

function sendFile(blob){
  var fd = new FormData()
  fd.append('uploadfield', blob, 'filename.png')

  return fetch('http://posttestserver.com/post.php', {
    method: 'post',
    body: fd
  })
  .then(function(res){
    return res.text()
  })
  .then(function(text){
    // response from a successful upload
    // location.href = new page
  })
}
&#13;
&#13;
&#13;

和es6

&#13;
&#13;
fetch('https://maxcdn.icons8.com/Share/icon/Logos//google_logo1600.png')
  .then(res => res.blob())
  .then(sendfile)
  
function sendFile(blob){
  const fd = new FormData()
  fd.append('uploadfield', blob, 'filename.png')

  return fetch('http://posttestserver.com/post.php', {
    method: 'post',
    body: fd
  })
  .then(res => res.text())
  .then(text => {
    // response from a successful upload
    // location.href = new page
  })
}
&#13;
&#13;
&#13;

如果你想在客户端使用IndexedDB Api存储blob,它可以更好地存储blob

相关问题