Angular-如何制作文件上传服务?

时间:2018-10-18 18:18:15

标签: angular typescript file

我发现使用服务上传图像很有用,但是我无法恢复在DateDemo2之后设置的import Foundation import XCTest class DateDecodeTests: XCTestCase { class DateDemo :Decodable { var dates : [Date] var eventsDateTimes : [Date]? var eventsDateTimes2 : [Date]? } class DateDemo2 : DateDemo { var eventsDateTimes3 : [Date]? } func testDateDecoding() throws { let json = """ { "dates": ["2018-10-17T23:00:00.000+01:00", "2018-10-18T00:30:00.000+01:00"], "eventsDateTimes": ["2018-10-18T22:00:00.000+02:00", "2018-10-31T00:30:00.000+01:00", "2018-11-08T20:00:00.000+01:00"], "eventsDateTimes2": [], } """.data(using: .utf8)! let decoder : JSONDecoder = JSONDecoder.myDefaultJsonDecoder let date = try decoder.decode(DateDemo.self, from: json) print(date.dates) print(date.eventsDateTimes) print(date.eventsDateTimes2) // It prints out: // [2018-10-17 22:00:00 +0000, 2018-10-17 23:30:00 +0000] // Optional([2018-10-18 20:00:00 +0000, 2018-10-30 23:30:00 +0000, 2018-11-08 19:00:00 +0000]) // Optional([]) } func testDateDecodingWithHierarchy() throws { let json = """ { "dates": ["2018-10-17T23:00:00.000+01:00", "2018-10-18T00:30:00.000+01:00"], "eventsDateTimes": ["2018-10-18T22:00:00.000+02:00", "2018-10-31T00:30:00.000+01:00", "2018-11-08T20:00:00.000+01:00"], "eventsDateTimes2": [], "eventsDateTimes3": ["2018-10-18T22:00:00.000+02:00", "2018-10-31T00:30:00.000+01:00", "2018-11-08T20:00:00.000+01:00"], } """.data(using: .utf8)! let decoder : JSONDecoder = JSONDecoder.myDefaultJsonDecoder let date = try decoder.decode(DateDemo2.self, from: json) print(date.dates) print(date.eventsDateTimes) print(date.eventsDateTimes2) print(date.eventsDateTimes3) // It prints out: // [2018-10-17 22:00:00 +0000, 2018-10-17 23:30:00 +0000] // Optional([2018-10-18 20:00:00 +0000, 2018-10-30 23:30:00 +0000, 2018-11-08 19:00:00 +0000]) // Optional([]) // nil ---> ??? Why is this nil? assert(date.eventsDateTimes3 != nil, "eventsDateTimes3 must not be nil") } } extension JSONDecoder { static var myDefaultJsonDecoder: JSONDecoder { let decoder = JSONDecoder() decoder.dateDecodingStrategy = .formatted(DateFormatter.myDefaultDateFormatter) return decoder } } extension DateFormatter { static var myDefaultDateFormatter: DateFormatter { let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZ" return formatter } } 值。

url

如何恢复render.onload// service export class UploadService { constructor(private alertService: AlertService) {} uploadPhoto(event: Event) { const file = (event.target as HTMLInputElement).files[0]; if (file.type === 'image/png' || file.type === 'image/jpeg' || file.type === 'image/jpg') { const reader = new FileReader(); let url; reader.onload = () => { url = reader.result; }; reader.onerror = (error: any) => { this.alertService.error(`Error ao carregar a imagem: ${error}`); return; }; reader.readAsDataURL(file); return { File: file, Url: url }; } else { this.alertService.error('Formato inválido. Somente imagens do formato Png, Jpeg e Jpg são permitidos.'); return; } } } // component uploadBanner(event: Event) { const Upload = this.uploadService.uploadPhoto(event); if (Upload) { this.urlBanner = Upload.Url; this.shop.banner = Upload.File; } }

1 个答案:

答案 0 :(得分:1)

您将其视为同步操作,但事实并非如此。您必须使用PromiseObservable来解决此问题。并在您的onload事件触发时返回数据。

export class UploadService {

  constructor(private alertService: AlertService) {}

  uploadPhoto(event: Event): Promise<{file: any, url: string}> { {
    return new Promise((resolve, reject) => {
      const file = (event.target as HTMLInputElement).files[0];

      if (file.type === 'image/png' || file.type === 'image/jpeg' || file.type === 'image/jpg') {
        const reader = new FileReader();
        let url;
        reader.onload = () => {
          resolve({file, url: reader.result})
        };
        reader.onerror = (error: any) => {
          this.alertService.error(`Error ao carregar a imagem: ${error}`);
          reject(error)
        };
        reader.readAsDataURL(file);
      } else {
        let error = 'Formato inválido. Somente imagens do formato Png, Jpeg e Jpg são permitidos.'
        this.alertService.error(error);
        reject(error);
      }
    }
  }
}

组件

// component
uploadBanner = async (event: Event) => {
  const url = await this.uploadService.uploadPhoto(event);
  console.log(url)
}