简体   繁体   English

通过节点js上传base64(文件)到php服务器

[英]upload base64 (file) to php server via node js

I currently have a situation where FormData doesn't work for me.我目前遇到的情况是 FormData 不适合我。 I'm using a specific "engine" Adobe CEP which is a little antiquated and the formData causes issues.我正在使用一个有点过时的特定“引擎”Adobe CEP,并且 formData 会导致问题。 My solution was to upload a file directly via base64 encoding.我的解决方案是通过 base64 编码直接上传文件。 From Node JS I do:从 Node JS 我做:

let buff = new Buffer(filePath);
let base64data = buff.toString('base64');
console.log(base64data);

The console.log gives me the string: console.log 给了我字符串:

Li4vLi4vLi4vLi4vLi4vLi4vLi4vVXNlcnMvb21hcmd1em1hbi8vRGVza3RvcC9Zb28vYWkyaHRtbC1vdXRwdXQvaG9tZS1wcm8tQXJ0Ym9hcmRfMS5qcGc=

  axios.post(API_ENDPOINT, base64data)
  .then(res => console.log(res))

From here I upload to a php server via axios.从这里我通过 axios 上传到 php 服务器。 The server receives it and I do:服务器收到它,我这样做:

<?php
$data = json_decode( file_get_contents('php://input') );
file_put_contents('testmeimg.jpg', base64_decode($data));
echo 'completed';
?>

another attempt另一次尝试

$data = file_get_contents('php://input');
file_put_contents('testmeimg.jpg', base64_decode($data));
var_dump($data);

"string(120) "Li4vLi4vLi4vLi4vLi4vLi4vLi4vVXNlcnMvb21hcmd1em1hbi8vRGVza3RvcC9Zb28vYWkyaHRtbC1vdXRwdXQvaG9tZS1wcm8tQXJ0Ym9hcmRfMS5qcGc="
"

The file correctly gets saved to my server but it's damaged and unreadable.该文件正确保存到我的服务器,但已损坏且无法读取。 It also appears with zero bytes.它也以零字节出现。 Any idea what I'm doing wrong?知道我做错了什么吗? or how I should handle this b64?或者我应该如何处理这个 b64?

Thanks to the great help by @rickdenhaan aka the man.感谢@rickdenhaan aka 的大力帮助。 I changed my node buffer code to:我将节点缓冲区代码更改为:

   let buff = new Buffer(fs.readFileSync(filePath));
    let base64data = buff.toString('base64');

Previously I wasn't sending the file buffer only the path as a buffer.以前我不是只发送文件缓冲区作为缓冲区的路径。

Then on the php side this worked:然后在 php 端这工作:

$data = file_get_contents('php://input');
file_put_contents('testmeimg.jpg', base64_decode($data));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM