从javascript发送时如何保存图像服务器端 [英] How to save image server side when send from javascript

查看:120
本文介绍了从javascript发送时如何保存图像服务器端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过阅读一堆教程来制作拖放上传脚本,但它们只涵盖了javascript部分,我在php部分遇到了问题。

I'm was making a drag and drop upload script by reading a bunch of tutorials, but they only cover the javascript part, and i'm having issues on the php part.

我正在上传图片:

$('#drop-zone').bind('drop', drop);

function drop(e) {
    e.stopPropagation();
    e.preventDefault();
    e.dataTransfer = e.originalEvent.dataTransfer;
    traverseFiles(e.dataTransfer.files);
}

traverseFiles为每个文件创建一个foreach循环并调用上传函数,我在那里做这个:

traverseFiles makes a foreach loop for every file and calls upload funcion, there i do this:

xhr = new XMLHttpRequest();

//some event listners for processing, on load

xhr.open("post", "core/plugins/upload/upload.class.php", true);

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);

然后在php中我发现使用这将获得图像的原始数据

then in php i found using this will get me raw data of the image

$file = file_get_contents('php://input');

编辑:找到解决方案

$fh = fopen($savedir, 'w') or die("can't open file");
fwrite($fh, $file);
fclose($fh);


推荐答案

假设您已设法从中获取原始文件PHP输入,它可能会被base64编码。一个简单的例子就是这样做:

Assuming you have managed to get the raw file from the PHP input, it's likely going to be base64 encoded. A simple example would be to do this:

<?php
//decode file
$image = base64_decode($file);

// write it
$filename = "myfile.png";
$fh = fopen($filename, 'w') or die("can't open file");
fwrite($fh, $image);
fclose($fh);

编辑
查看评论,文件未编码作为请求的结果。

Edit See comments, the file wasn't encoded as a result of the request.

这篇关于从javascript发送时如何保存图像服务器端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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