通过 XMLHttpRequest 从 HTML5 文件系统上传文件 [英] Upload file from HTML5 Filesystem by XMLHttpRequest

查看:22
本文介绍了通过 XMLHttpRequest 从 HTML5 文件系统上传文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试上传存储在 Google Chrome 文件系统中的一些图像.但我无法上传图片.知道怎么做吗?

Trying to Upload some Images stored in Filesystem of Google Chrome. But Im not able to upload the Image. Any Idea how to do it?

服务器收到一个空数组.posttest.php 的代码就是 print_r($_POST)

The Server receives an empty array. The Code of posttest.php is just print_r($_POST)

 var xhr = new XMLHttpRequest();
    xhr.open('POST', '/posttest.php', true);
    xhr.onload = function(e) {
        if (this.status == 200) {
            console.log(this.responseText);
        }
    };
    window.resolveLocalFileSystemURL(image, function(fileEntry) {
        fileEntry.file(function(file) {
            var reader = new FileReader();
            reader.onloadend = function(e) {
                var formData = new FormData();
                formData.append('image', this.result);
                xhr.send(formData);
            };
            reader.readAsText(file);
        });
    });

推荐答案

这是在 chrome 中为我工作的 Javascript 函数

this is the Javascript function that worked for me in chrome

function upload(filename) {	

	var xhr = new XMLHttpRequest();
	xhr.open("post", "upload.php", true);

	window.resolveLocalFileSystemURL = window.resolveLocalFileSystemURL || window.webkitResolveLocalFileSystemURL;

	filename = 'filesystem:http://localhost/temporary/' + filename;
	window.resolveLocalFileSystemURL(filename, function(fileEntry) {		
		fileEntry.file(function(file) {
			xhr.setRequestHeader("Content-Type", "multipart/form-data");
			xhr.setRequestHeader("X-File-Name", file.name);
			xhr.setRequestHeader("X-File-Size", file.size);
			xhr.setRequestHeader("X-File-Type", file.type);
		    xhr.send(file);
		});
	});

}

现在大多数人认为跳过upload.php 是理所当然的.但这很重要,所以我把它贴在这里:

Now most people on the skip the upload.php taking it for granted. But it is very important and so I paste it here:

<?php
    // I had to figure out what is getting passed using var_dump($_SERVER)
	$fn = (isset($_SERVER['HTTP_X_FILE_NAME']) ? $_SERVER['HTTP_X_FILE_NAME'] : false);
	if ($fn) {
		// AJAX call
		file_put_contents(
			'uploads/' . $fn,
			file_get_contents('php://input')
		);
		echo "$fn uploaded";
		exit();	
	}
?>

希望这对某人有所帮助,我浪费了一整天的时间来解决这个问题!

Hope this helps someone, I wasted an entire day to figure this out !

这篇关于通过 XMLHttpRequest 从 HTML5 文件系统上传文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆