【问题标题】:file upload not working in react native with multipart form data api nodejs文件上传无法使用多部分表单数据 api nodejs 在本机反应
【发布时间】:2020-09-21 04:46:21
【问题描述】:

我正在尝试使用 nodejs multipart api 上传带有 react native 的图像文件,但文件没有从 FE 发送。如果我控制台 req.files 它在服务器端未定义。这是我的反应原生代码:

       var options = {
           title: 'Select Image',
           storageOptions: {
               skipBackup: true,
               path: 'images'
           }
       };
       ImagePicker.showImagePicker(options, (response) => {
           console.log('Response = ', response);
           if (response.didCancel) {
               console.log('User cancelled image picker');
           } else if (response.error) {
               console.log('ImagePicker Error: ', response.error);
           } else if (response.customButton) {
               console.log('User tapped custom button: ', response.customButton);
           } else {
               console.log('User selected a file form camera or gallery', response);
               const data = new FormData();
               data.append('name', 'avatar');
               data.append('file', {
                   uri: response.uri,
                   type: response.type,
                   name: response.fileName
               });
               const config = {
                   method: 'POST',
                   headers: {
                       'Accept': 'application/json',
                       'Content-Type': 'multipart/form-data',
                   },
                   body: data,
               };
               fetch("http://myapi.com/api/v1/user", config)
                   .then((checkStatusAndGetJSONResponse) => {
                       console.log(checkStatusAndGetJSONResponse);
                   }).catch((err) => { console.log(err) });
           }
       }
       )

和 Nodejs 代码:

const storage = multer.memoryStorage({
    destination:(req, file, callback) => {
        callback(null, '')
    }
});

const upload = multer({ storage: storage }).array('file');
    upload(req,res,(err) => {
        if(err) {
            console.log('ERROR: ',err);
            return res.end("Error uploading file.");
        }else{
            console.log('REQUEST: ',req.files);
        }
    });



我无法上传带有一些用户数据的图片,请让我知道这里做错了什么 谢谢

【问题讨论】:

    标签: node.js react-native multer


    【解决方案1】:

    当您在正文中发送表单数据时,它只会保存该表单数据。

    如果您想发送表单数据和一些其他数据,请尝试将表单数据附加到另一个对象中,然后将其他数据附加到具有键值对的同一对象中。

    我创建了用户注册表单,其中有一些输入字段和个人资料上传。 对于上传,我使用了“ngx-file-drop”。

    喜欢:-

    const body = {};
    body['formData'] = formValues;
    body['fileData'] = this.fileDataArray;
    

    这里的ts代码如下。

    dropped(files: NgxFileDropEntry[]) {
        this.fileError = false;
        this.files = [];
        this.files = files;
        for (const droppedFile of files) {
          // Is it a file?
          if (droppedFile.fileEntry.isFile && this.isFileAllowed(droppedFile.fileEntry.name)) {
            this.filesArray.push(droppedFile);
            const fileEntry = droppedFile.fileEntry as FileSystemFileEntry;
             const formData: FormData = new FormData();
            fileEntry.file((file: File) => {
              
            });
            fileEntry.file((file: File) => {
              this.dropFilePath.push(droppedFile.relativePath);
              // append form data
              formData.append('upload', file, droppedFile.relativePath);
              this.dropFile.push(file);
              this.dropFileFlag = true;
            });
          } else {
            // It was a directory (empty directories are added, otherwise only files)
            const fileEntry = droppedFile.fileEntry as FileSystemDirectoryEntry;
            this.dropFilePath = [];
            this.dropFile = [];
            this.files = [];
    
            this.toaster.error('only this file are allowed : [".jpg", ".jpeg",".gif",".png"]', 'Error', {
              positionClass: 'toast-top-full-width',
            });
            break;
          }
        }
      }
    

    和html代码是。

    <ngx-file-drop [disabled]="isPreview ? true : null" dropZoneLabel="Drop files here" (onFileDrop)="dropped($event)" (onFileOver)="fileOver($event)"(onFileLeave)="fileLeave($event)">
    <ng-template ngx-file-drop-content-tmp let-openFileSelector="openFileSelector">
        <span [attr.disabled]="isPreview ? true : null" class="btn">Drop files here or</span>
           <span [attr.disabled]="isPreview ? true : null" (click)="openFileSelector()" class="btn btn-link">click to upload</span>
    </ng-template>
    </ngx-file-drop>
    

    在表单提交时,您可以这样做。

    onSubmit() {
        this.submitted = true;
    
        if (this.form.invalid || (this.submitted && this.fileError)) {
          this.toaster.error('Invalid form data..!!', 'ERROR');
          return;
        }
        const formData = this.form.value;
        this.fileDataArray.push(formData.getAll('upload'));
        console.log('this.fileDataArray-------->', this.fileDataArray);
        const body = {};
        body['formData'] = formData;
        body['fileData'] = this.fileDataArray;
        console.log('body------>', body);
        // call below your api function
       }
    

    【讨论】:

    • 我认为它的角度代码,但我想要 react-native @nilesh-solanki
    • @VishalRana 是的,它的角度,我提供了一个想法,您可以在具有不同 kev 值对的公共对象中发送 formdata 和用户其他数据。
    • 我的任务是在 react-native 中上传文件,使用 angular 很容易做到。
    • 您是否检查过您从客户端发送的数据附加名称和您在服务器端获取的数据是否相同。
    • 如果对您有帮助,请查看此链接。 heartbeat.fritz.ai/…>
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多