php获取表单图片base64,表单如何提交base64的格式的图片?

  • Post author:
  • Post category:php


后端是用PHP的$_FILES变量获取提交的文件。

正常的表单提交是这样。

<h2>正常表单提交,enctype=multipart/form-data</h2>

<form action=”upload.php” method=”post” enctype=”multipart/form-data” id=”form-1″>

<label for=”file-1″>file</label>

<input type=”file” name=”file” id=”file-1″ />

<input type=”submit” value=”submit” />

</form>

我这里的情况是,上传的文件,是来自外部的一串base64字符串,这里该如何转变,才能实现模拟表单提交,后台不需要更改代码。

PS:

我尝试把base64放在FormData对象里面,但后台的$_FILES变量依旧不能识别

function sendFormByBase64(){

var form = document.getElementById(‘form-2’);

var formData = new FormData();

var base64 =’/* 这里面是base64字符串 */’;

formData.append(‘file’, base64);

var xhr = new XMLHttpRequest();

xhr.open(‘POST’, form.action, true);

xhr.send(formData);

}

PS2:再附抓包图

base64的抓包

bVb0b0

正常post提交表单文件的抓包

bVb0b1

你这个问题我刚刚遇到了,但我用tornado+ajax,希望对你有帮助

base64的图片数据,你直接用普通表单(

xhr.setRequestHeader(“Content-Type”, “application/x-www-form-urlencoded “);

),当作字符串传后服务器就可以了,但是因为一些特殊字符的表单数据很危险,所以要进行url编码

encodeURIComponent()

function sendimg(b64img){

var xhr = new XMLHttpRequest();

xhr.onreadystatechange = function () {

if (xhr.readyState == 4) {

if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {

//

} else {

//

}

}

};

xhr.open(“post”, “/upload.php”, true);

xhr.setRequestHeader(“Content-Type”, “application/x-www-form-urlencoded “);

xhr.send(“img=”+encodeURIComponent(shared.imageDataURL));

}

服务器接受到表单

name

img

的数据即为url编码后的base64数据,解码后就是你要的

关于ajax和后台处理的代码可以看看我的小项目:)

Ps:木有看时间,题主在上半年提问的QAQ, 现在问题应该已经解决了~ o(∩∩)o…

推荐阅读:表单如何提交base64的格式的图片?后端是用PHP的$_FILES变量获取提…