如何上传以前存储在本地存储的图像?

How Might I Upload an Image Previously Stored in LocalStorage?

本文关键字:存储 图像      更新时间:2023-09-26

我有一个html5移动web应用程序(http://app.winetracker.co),我正在研究的功能,记住用户的状态,当他们回到他们的浏览器中的应用程序(总是自动刷新iOS safari)。我通过本地存储存储URL和表单字段数据。其中一个表单字段数据项是用于图像的文件输入。我成功地通过画布将图像转换为base64并将其存储到localStorage。

function storeTheImage() {
    var imgCanvas = document.getElementById('canvas-element'),
        imgContext = imgCanvas.getContext("2d");
    var img = document.getElementById('image-preview');
    // Make sure canvas is as big as the picture BUT make it half size to the file size is small enough
    imgCanvas.width = (img.width/4);
    imgCanvas.height = (img.height/4);
    // Draw image into canvas element
    imgContext.drawImage(img, 0, 0, (img.width/4), (img.height/4));
    // Get canvas contents as a data URL
    var imgAsDataURL = imgCanvas.toDataURL("image/png");
    // Save image into localStorage
    try {
        window.localStorage.setItem("imageStore", imgAsDataURL);
        $('.localstorage-output').html( window.localStorage.getItem('imageStore') );
    }
    catch (e) {
        console.log("Storage failed: " + e);
    }
}
function readURL(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function (e) {
            $('#image-preview').attr('src', e.target.result);
            storeTheImage(); 
        }
        reader.readAsDataURL(input.files[0]);
    }
}
$('.file-input').on('change', function() {
    readURL(this);
});

查看这个jsFiddle: https://jsfiddle.net/tonejac/ceLwh9qp/19/

我如何将localStore图像dataURL字符串转换回图像文件,以便我可以将其上传到服务器?

如何将localStore图像dataURL字符串转换回图像文件

看到你的小提琴,Javascript窗格第25行。

 // recompose image :
var imgRecomposed = document.createElement('img');
$('.image-recomposed').append(imgRecomposed);
imgRecomposed.src = window.localStorage.getItem('imageStore');

我们创建一个图像元素,并用存储的'dataImage'的数据填充src属性。

In your Fiddle:

// Save image into localStorage
    try {
        window.localStorage.setItem("imageStore", imgAsDataURL);
        $('.localstorage-output').html( window.localStorage.getItem('imageStore') );
    }
    catch (e) {
        console.log("Storage failed: " + e);
    }

在try/catch语句中加入以下任意语句:

$('#canvas-element').context.drawImage(imgAsDataURL);
$('#canvas-element').context.drawImage(imgAsDataURL, 0, 0);
$('#canvas-element').replace(imgAsDataURL);

这将把存储的图像放入您所显示的画布中。它已经是一个"图像"了——你可以用它作为元素的src。将它发送到服务器取决于您所拥有的环境-基本上是Ajax POST或类似的发送base64字符串?

您首先必须将此dataURL转换为blob,然后使用FormData对象将此blob作为file发送。

要将dataURL转换为blob,我确实使用了这个答案中的函数。

function upload(dataURI, url){
  // convert our dataURI to blob
  var blob = dataURItoBlob(dataURI);
  // create a new FormData
  var form = new FormData();
  // append the blob as a file (accessible through e.g $_FILES['your_file'] in php and named "your_filename.extension")
  form.append('your_file', blob, 'your_filename.'+blob.type.split('image/')[1]);
  // create a new xhr
  var xhr = new XMLHttpRequest();
  xhr.open('POST', url);
  // send our FormData
  xhr.send(form);
  }
// from https://stackoverflow.com/questions/4998908/convert-data-uri-to-file-then-append-to-formdata/5100158#5100158
function dataURItoBlob(dataURI) {
    // convert base64/URLEncoded data component to raw binary data held in a string
    var byteString;
    if (dataURI.split(',')[0].indexOf('base64') >= 0)
        byteString = atob(dataURI.split(',')[1]);
    else
        byteString = unescape(dataURI.split(',')[1]);
    // separate out the mime component
    var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
    // write the bytes of the string to a typed array
    var ia = new Uint8Array(byteString.length);
    for (var i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
    }
    return new Blob([ia], {type:mimeString});
}
var savedIntoLocalStorage = 'data:image/png;base64,...=';
// execute the request
upload(savedIntoLocalStorage, 'http://yourserver.com/upload.php');