用uniapp做图片上传的时候出现了跨域问题
前端:uniapp
后端:thinkphp
Access to XMLHttpRequest at 'xxxx' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.
只有上传图片的时候才报这错 其他获取、发送的请求都不会报错。
报错的代码:
uploadBackPic() {
uni.chooseImage({
count: 1,
sizeType: ['original'],
success: (imageRes) => {
const tempFrontPicPath = imageRes.tempFilePaths[0]
uni.uploadFile({
url: '/index/upload/uploadFile?token=' + uni
.getStorageSync('token'),
filePath: tempFrontPicPath,
header: {
'content-type': 'multipart/form-data'
},
name: 'file',
success: (res) => {
let data = JSON.parse(res.data)
this.cardBack = data.picUrl
uni.showToast({
title: '图片上传成功',
icon: 'success'
}, 500)
this.showBack = true
}
})
}
})
},
一直找不到什么原因,跨域也设置过了 在public/index.php设置的跨域
header("Access-Control-Allow-Origin: *");//允许所有地址跨域请求
header("Access-Control-Allow-Methods: HEAD, GET, POST, PUT, PATCH, DELETE, OPTIONS");//请求方式
header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept,TOKEN, Access-Control-Request-Method,Access-Control-Request-Headers, Authorization");//允许接收的header头参数 例如:需要传参userid,则需要这里配置一下
header('Content-Type: application/json');
$method = $_SERVER['REQUEST_METHOD'];
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: HEAD, GET, POST, PUT, PATCH, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, TOKEN, Access-Control-Request-Method, Access-Control-Request-Headers, Authorization');
header('HTTP/1.1 200 OK');
exit();
}
用base64上传不会有这个情况,而且用 uniapp的getFileSystemManager 也会报错
[system] API `getFileSystemManager` is not yet implemented
然后用原生的JS 转为base64后上传成功了
下面附上代码
uploadPic() {
uni.chooseImage({
count: 1,
sizeType: ['original'],
success: async (imageRes) => {
const tempFilePath = imageRes.tempFilePaths[0];
try {
const response = await fetch(tempFilePath);
const blob = await response.blob();
const reader = new FileReader();
reader.onload = (event) => {
const base64 = event.target.result.split(',')[1];
this.$myRequest({
url: 'index/upload/UploadImgBase64',
method: 'post',
data: {
token: uni.getStorageSync('token'),
img: base64,
}
}).then((res) => {
console.log(res);
this.goods_img = res.data.imgUrl;
this.showImg = true;
uni.showToast({
title: '图片上传成功',
icon: 'success'
}, 500);
});
};
reader.readAsDataURL(blob);
} catch (error) {
console.error('无法获取或转换图像:', error);
}
}
});
},
后端thinkphp的代码 (不是我写的):
public function UploadImgBase64()
{
//base64字符串上传图片
ini_set('memory_limit', '100M');
$b = file_get_contents('php://input');
$b = json_decode($b, true);
$imgInfo = base64_decode($b['img']);
$file_name = md5($imgInfo);
$date = date('Ymd');
@mkdir(config('upload.img_path'));//创建目录
@mkdir(config('upload.img_path') . '/' . $date);//创建目录
$imgType = $b['img_name'] ?? 'image/jpg';
$imgType = explode('/', $imgType);
$imgType = $imgType[1] ?? 'jpg';
if (!in_array($imgType, ['jpg', 'png', 'gif', 'jpeg'])) {
return json(['code' => -1, 'msg' => '只允许上传png,jpg,gif格式图片']);
}
$imgType = '.' . $imgType;
$file_path = config('upload.img_path') . '/' . $date . '/' . $file_name . $imgType;
file_put_contents($file_path, $imgInfo);
return json(['code' => 200, 'msg' => '上传成功', 'imgUrl' => 'https://' . $_SERVER["HTTP_HOST"] . '/' . config('upload.img') . '/' . $date . '/' . $file_name . $imgType]);
}
config/upload.php
dirname(__FILE__, 2) . '/public/img',//文件上传
'img' => 'img',//相对于public目录下
'code_path' => dirname(__FILE__, 2) . '/public/code',//文件上传
'code_img' => 'code',//相对于public目录下
];