服务器仅在从React Native上传文件时接收元数据

niwlg2el  于 2023-05-18  发布在  React
关注(0)|答案(1)|浏览(155)

React Native客户端和NestJS服务器我正在尝试录制音频并将文件发送到服务器。当我尝试用Postman和React测试时,API端点似乎工作得很好。然而,当我用React Native上传一个文件时,服务器只接收元数据,但内容是一个empty Buffersize 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
}
qrjkbowd

qrjkbowd1#

终于让它工作了,尽管事实上类型是错误的。(不得不将文件存储到any

.
.
.
        const file = {
          uri: recordingUri,
          name: "audio.m4a",
          filename: "audio.m4a",
          type: fileType,
        };

        const formData = new FormData();
        formData.append("file", file as any);

        const response = await fetch(endpointUrl, {
          method: "POST",
          body: formData,
          headers: {
            "Content-Type": "multipart/form-data",
          },
        });
        );

相关问题