因为我在使用web访问云托管,但是云托管部署的服务的接口,接收不到我发送的formdata中的file文件
#这部分是接口
static addImageBanner(imageName: File) {
const formData = new FormData();
formData.append('file', imageName);
return callCloud(`${ROOM_BASE_URL}/Add_ImgBanner`, {
method: "post",
headers: {
// 'Content-Type': 'application/octet-stream',
"Content-Type": "multipart/form-data",
"X-File-Name": imageName.name,
},
data: formData,
});
}
这个是callCloud的封装
export async function callCloud(path: string, options: any) {
// 打印携带的数据
// console.log('携带的数据:', dataa);
const c1 = new cloud.Cloud({
identityless: true,
resourceAppid: "******",
resourceEnv: "********",
});
if (options.data && typeof options.data.entries === 'function') {
for (let [key, value] of options.data.entries()) {
console.log(key, value);
}
} else {
console.log("options.data is undefined or does not have entries method");
}
await c1.init();
let fullUrl = `${path}`;
console.log(fullUrl);
// 处理查询参数
if (options.params && Object.keys(options.params).length > 0) {
const queryString = Object.entries(options.params)
.map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value as string)}`)
.join('&');
fullUrl += `?${queryString}`;
}
const callContainerPromise = c1.callContainer({
path: fullUrl,
method: options.method || "GET",
header: {
"X-WX-SERVICE": "ypyz", // xxx中填入服务名称(微信云托管 - 服务管理 - 服务列表 - 服务名称)
...options.headers,
},
data: options.data || {},
});
const timeoutPromise = new Promise((_, reject) =>
setTimeout(() => reject(new Error("请求超时")), 15000)
);
try {
const result = await Promise.race([callContainerPromise, timeoutPromise]);
console.log(`微信云托管调用结果${result.errMsg} | callid:${result.callID}`);
console.log(result);
return result.data;
} catch (error) {
console.error("Error in callCloud:", error);
throw error;
}
}
这个是后端代码
def post(self):
rp = RequestParser()
rp.add_argument('file', action='append', required=True, location='files', type=FileStorage)
args = rp.parse_args()
files = args.get('file')
try:
# files = request.data
if not files:
current_app.logger.error('没有上传文件')
return {'code': 400, 'msg': '请上传图片'}
else:
img_list = ImgBanner.query.order_by(ImgBanner.created_at.asc())
current_app.logger.info(f"数据库中图片数量: {img_list.count()}")
# FileUpload
# 获取文件名
# for uploaded_file in files:
base_dir = Path(__file__).resolve().parent.parent.parent
if not os.path.exists(os.path.join(base_dir / 'static/roomimage')):
try:
os.makedirs(os.path.join(base_dir / 'static/roomimage'))
current_app.logger.info(f"当前路径{base_dir / 'static/roomimage'}")
current_app.logger.info(f"Directory roomimage created successfully.")
except Exception as e:
current_app.logger.error(f"Failed to create directory roomimage: {e}")
return {'code': 20003, 'msg': '无法创建目录'}
file_name = request.headers.get('X-File-Name', 'default.jpg')
# file_name = uploaded_file.filename
img_name = f"{uuid.uuid4().hex}"
uuid_image_name = img_name + '-' + f'{file_name}'
temp_file_path = os.path.join(base_dir / 'static/roomimage', uuid_image_name)
# 保存文件对象到临时文件
files[0].save(temp_file_path)
# with open(temp_file_path, 'wb') as f:
# f.write(files)
# files.save(temp_file_path)
result = FileUpload.upload_main(uuid_image_name)
if result['code'] == 200:
file_list = [{'fileid': result['data']['file_id'], 'max_age': 30}]
image_url = FileUpload.get_download_url(file_list)
url = json.dumps(image_url['data']['file_list'][0]['download_url']).replace('"', '')
new_image = ImgBanner(file_id=result['data']['file_id'], image_url=url, image_name=uuid_image_name)
db.session.add(new_image)
try: # 需要用到数据库事务处理
db.session.commit()
except Exception as e:
current_app.logger.error(f"Failed to save image to database: {e}")
db.session.rollback()
return {'code': 20004, 'msg': '保存图片到数据库失败'}
else:
current_app.logger.error(f"Failed to upload file: {result['msg']}")
return {'code': 20002, 'msg': '上传失败'}
return {'code': 200, 'msg': '上传成功'}
except Exception as e:
current_app.logger.error(f'处理上传文件时出错: {e}')
return {'code': 500, 'msg': '服务器内部错误'}
但是我选择图片上传后报错
就是在云托管服务上拿不到formdata中的file字段文件,但是在本地测试的时候可以拿到,没有问题,有没有大佬给解决一下啊
1、callContainer不是标准http接口,会有不同。
2、callContainer接口有请求大小限制,不建议用于文件上传