401在已签名的上传预设中将图像上传到特定文件夹中的Cloudinary时出现未经授权的错误



我有一个社交媒体应用程序,当用户想要上传个人资料图片时,他们必须从服务器获得签名。当我删除前端的上传预设时,这个代码有效,但我想要上传预设,这样用户就可以上传到特定的文件夹,而且这是一个签名的上传预设,那么为什么我会收到401未经授权的错误呢?

在后端上

const generateSignature = async (req, res) => {
/* It's just getting the current time in seconds. */
const timestamp = Math.round(new Date().getTime() / 1000);
try {
const signature = cloudinary.utils.api_sign_request(
{
timestamp,
},
cloudinaryConfig.api_secret
);

res.status(200).json({
success: true,
timestamp,
signature,
api_key: cloudinaryConfig.api_key,
cloud_name: cloudinaryConfig.cloud_name,
});
} catch (err) {
console.log(err);
res.status(500).json({ success: false, message: "server error try again" });
}
};

在前端上

const { timestamp, signature, api_key, cloud_name } =
signatureResponse.data;
const formData = new FormData();
formData.append("file", image);
formData.append("upload_preset", "uploadProfilePicture");// if i remove this line it works 
formData.append("api_key", api_key);
formData.append("cloud_name", cloud_name);
formData.append("signature", signature);
formData.append("timestamp", timestamp);
console.log(formData);
const cloudinaryResponse = await axios.post(
`https://api.cloudinary.com/v1_1/${cloud_name}/image/upload`,
formData
);

在当前代码中,您仅使用timestamp参数为上传请求生成身份验证签名,但实际上需要包括您作为API调用的一部分传递给Cloudinary的所有参数,不包括filecloud_nameapi_keyresource_type

换句话说,根据您的示例,如果您想向Cloudinary发送upload_preset参数,则需要在传递给api_sign_request()的哈希中包含upload_preset: "uploadProfilePicture",以便在上载请求中发送的该参数包含在签名生成中。这就是为什么从上传请求中删除该参数会导致成功上传的原因,因为此时您将传递与生成签名相同的值(即仅timestamp(。

这同样适用于您想要传递给Cloudinary的任何其他参数。例如,如果要将use_filename参数集发送到true,则还需要将其包含在签名生成代码中。实际上,您的前端代码应该将您想要发送到Cloudinary的所有参数发送到服务器,以便您的后端可以基于这些参数生成签名。

与上述无关,请注意,resource_typecloud_name参数可以从FormData中删除。这是因为这两个都已经通过API URL端点(即https://api.cloudinary.com/v1_1/${cloud_name}/image/upload(传递给Cloudinary,其中将对cloud_name进行插值,而resource_type将为image

还请参阅以下参考资料,以便直接上传和生成签名以与Cloudinary API交互。它包括进一步的示例和分步指南:https://cloudinary.com/documentation/upload_images#uploading_with_a_direct_call_to_the_rest_api

相关内容

最新更新