【发布时间】:2023-02-13 13:28:38
【问题描述】:
我正在研究 Reactjs 和 Php,实际上我正在尝试将图像上传到服务器,图像正在上传但是每当我尝试打开图像然后显示“我们不支持这种文件格式”时,我该如何解决这个问题?
- 我正在发送包含多部分表单数据的表单数据,在 php (api) 中我使用 base64 图像将图像上传到服务器
- 我将图像发送到 axios (api) 的方法是正确的还是 php 代码有问题
这是我的 nextjs 代码
const handleSubmit: FormEventHandler<HTMLFormElement> = async (e) => { var imagefile = document.querySelector('#file'); formData.append("file", imagefile.files[0]); const response = await axios({ method: "post", url: "https://xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/", data: formData, headers: { "Content-Type": "multipart/form-data" }, }).then(function (response) { alert('respone is '+ response.data.msg); }).catch(function (error) { alert('respone is '+ error); console.log("failed to get recommend playlist"); console.log('error is '+ error.msg); }); }以下是我在 Php 端的 Api 代码
$data = json_decode(file_get_contents("php://input"), TRUE); $files=file_get_contents($_FILES["file"]["tmp_name"]); $image = base64_decode(explode( ',', $files)[1]); define('UPLOAD_DIR', 'uploads/'); $file_ext = strtolower( end(explode('.',$file_name))); $image_parts = explode(";base64,", $image); $image_type_aux = explode("image/", $image_parts[0]); $image_type = $image_type_aux[1]; $image_base64 = base64_decode($image_parts[1]); $file = UPLOAD_DIR . uniqid() . '.'.$file_ext; file_put_contents($file, $image_base64);
【问题讨论】:
标签: javascript php reactjs api next.js