如何将图像自动下载并保存到HTML中的指定文件夹?

时间:2019-02-19 08:56:39

标签: javascript html5

现在我已经完成了将图像保存到本地的操作,但是浏览器已保存到默认文件夹,如何修改代码以保存到指定文件夹?

function download(canvas,type) {                
    var imgdata = canvas.toDataURL(type);

    var fixtype = function (type) {
        type = type.toLocaleLowerCase().replace(/jpg/i, 'jpeg');
        var r = type.match(/png|jpeg|bmp|gif/)[0];
        return 'image/' + r;
    };

    imgdata = imgdata.replace(fixtype(type), 'image/octet-stream')

    var saveFile = function (data, filename) {
        var link = document.createElement('a');

        link.href = data;
        link.download = filename;

        var event = document.createEvent('MouseEvents');
        event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
        link.dispatchEvent(event);
    };

    saveImageCount++;

    var str = "" +saveImageCount;
    var pad = "0000";
    var ans = pad.substring(0, pad.length - str.length) + str;
    var filename = ans + '.' + type;

    saveFile(imgdata, filename);
}

1 个答案:

答案 0 :(得分:1)

每个浏览器中都有安全沙箱,在这些沙箱中javascript上下文不会受到干扰。本地文件系统就是其中之一,因此您无法强制将文件保存到自定义文件夹