1,安装上传插件

ionic cordova plugin add cordova-plugin-file-transfer

npm install @ionic-native/file-transfer --save

2, app.module 中引入

import { FileTransfer } from '@ionic-native/file-transfer/ngx';
import { File } from '@ionic-native/file/ngx';


@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [
   ],
  providers: [
  
    FileTransfer,
    File,
   }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

3,使用demo


import { FileTransfer, FileUploadOptions, FileTransferObject } from '@ionic-native/file-transfer/ngx';

@Injectable({
  providedIn: 'root'
})
/**
 * api 网络请求服务
 */
export class ApiService {
 
 constructor( private transfer: FileTransfer) { }


  /**
   * 上传图片逻辑 可再次封装
   * @param type 图片类型
   * @param uuid 图片uuid
   * @param filePath 本地路径
   * @param fileName 文件名
   */
  public uploadImage(type: any, uuid: string, filePath: string, fileName: String): Observable<any> {
    let url = this.baseUrl + this.UPLOAD_PIC;
    //上传的参数
    let options: {} = {
      fileKey: "file",
      fileName: fileName,
      chunkedMode: false,
      mimeType: "mulipart/form-data",
      params: {
        'token': this.token,
        'fileName': fileName,
        "imgtype": type,
        "bus_uuid": uuid
      }
    };
    const fileTransfer: FileTransferObject = this.transfer.create();
    return new Observable(result => {
      //开始正式上传
      fileTransfer.upload(filePath, url, options).then((data: any) => {
        if (this.isOK(data)) {
          result.next(data);
        } else {
          result.error(data.msg);
        }
      }, err => {
        result.error(err);
      });
    });
  }

}

 

Logo

开源鸿蒙跨平台开发社区汇聚开发者与厂商,共建“一次开发,多端部署”的开源生态,致力于降低跨端开发门槛,推动万物智联创新。

更多推荐