React Native客户端和NestJS服务器我正在尝试录制音频并将文件发送到服务器。当我尝试用Postman和React测试时,API端点似乎工作得很好。然而,当我用React Native上传一个文件时,服务器只接收元数据,但内容是一个empty Buffer
和size 0
。在stopRecording
处理程序中,我已经检查过,在发送请求之前,formData确实包含音频文件的内容。
组件内部的React Native代码
const AudioInput3 = () => {
const [recording, setRecording] = useState<Recording | null>(null);
const [recordingStatus, setRecordingStatus] = useState("idle");
const [audioPermission, setAudioPermission] = useState(false);
const startRecording = async () => {
try {
if (audioPermission) {
await Audio.setAudioModeAsync({
allowsRecordingIOS: true,
playsInSilentModeIOS: true,
});
}
const newRecording = new Audio.Recording();
await newRecording.prepareToRecordAsync(
Audio.RecordingOptionsPresets.HIGH
);
await newRecording.startAsync();
setRecording(newRecording);
setRecordingStatus("recording");
} catch (err) {
console.error("Failed to start recording", err);
}
};
async function stopRecording() {
try {
if (!recording) return;
if (recordingStatus === "recording") {
await recording.stopAndUnloadAsync();
const recordingUri = recording.getURI() as string;
const filename = `recording_${Date.now()}.caf`;
const filePath = FileSystem.documentDirectory + "recordings/";
setRecording(null);
setRecordingStatus("stopped");
const fileData = await FileSystem.readAsStringAsync(recordingUri, {
encoding: FileSystem.EncodingType.Base64,
});
const blob = new Blob([fileData], { type: "audio/x-caf" });
const file = new File([blob], filename, {
type: "audio/x-caf",
});
const fileSize = file.size;
const formData = new FormData();
formData.append("file", file);
const response = await fetch(urlResolver.uploadToStorage(), {
method: "POST",
body: formData,
headers: {
"Content-Type": "multipart/form-data",
"Content-Length": String(fileSize),
},
});
}
} catch (error) {
console.error(error);
}
}
我已经尽力了。
1.一些解决方案提到删除请求头,这不工作我。
1.将fetch替换为axios
也不起作用
1.关闭react-native-debugger
也不工作。
我的NestJS API端点如下。(当文件从React或Postman上传时,此功能正常工作)
@Post("upload")
@UseInterceptors(FileInterceptor("file"))
uploadFile(@UploadedFile() file: Express.Multer.File) {
console.log(file);
}
其返回以下结果。(空缓冲区和文件大小=== 0)
{
fieldname: 'file',
originalname: 'recording_1683615927273.caf',
encoding: '7bit',
mimetype: 'audio/x-caf',
buffer: <Buffer >,
size: 0
}
1条答案
按热度按时间qrjkbowd1#
终于让它工作了,尽管事实上类型是错误的。(不得不将文件存储到
any
)