当前位置: 动力学知识库 > 问答 > 编程问答 >

php - How to upload a file to an API

问题描述:

Let's suppose I have a PHP server. I am creating an API for this server. I would expect to receive a request, where

$_POST["FileContent"]

would contain the file content and

$_POST["FileName"]

would contain the name of the file. My problem is that I have not done anything like that and the only way I can upload a file in this moment is using an input of type file. If I just load the file in a binary way, then I would like to use a best-practice approach and I would also like to make sure that the content is really an image content and not a PHP upload injection, for instance. How can I do that?

网友答案:

You should base64 encode the file contents on the client-side, and base64 decode on the API side.

// client (pseudo-code)
data = {FileName: "someFileName", FileContents: base64Encode(someFile)}

// api
$fileContents = base64_decode($_POST['FileContents']);
$fileName     = $_POST['FileName'];

file_put_contents('path/to/upload/' . $fileName, $fileContents);
分享给朋友:
您可能感兴趣的文章:
随机阅读: