Skip to content

Instantly share code, notes, and snippets.

@Pierozi
Created July 13, 2022 15:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Pierozi/5e7657b931bdec3a465057aa5c7bb487 to your computer and use it in GitHub Desktop.
Save Pierozi/5e7657b931bdec3a465057aa5c7bb487 to your computer and use it in GitHub Desktop.
Angular S3 Upload Multipart
import {Injectable} from '@angular/core'
import {Observable} from 'rxjs'
import {HttpClient, HttpHeaders} from '@angular/common/http'
import {AuthService} from '../auth/auth.service'
export interface PresignResponse {
url: string
fields?: PresignFields
}
export interface PresignFields {
[key: string]: string
}
@Injectable({
providedIn: 'root'
})
export class S3uploadService {
constructor(
private http: HttpClient,
) {
}
public getUploadLink(file: File, url, cognitoAuth: boolean = false) {
const fileExtension = file.name.split('.').reverse()[0]
const body = {
extension: fileExtension
}
if (cognitoAuth) {
return this.http.post(url, body, {
withCredentials: true,
})
} else {
return this.http.post(url, body)
}
}
public upload(file: File, url: string, fields: PresignFields): Observable<any> {
const formData = new FormData()
// tslint:disable-next-line:forin
for (const k in fields) {
formData.append(k, fields[k])
}
formData.append('file', file)
return this.http
.post(url, formData, {
/*headers: new HttpHeaders({
'Content-Type': 'multipart/form-data'
}),*/
responseType: 'blob',
reportProgress: true,
withCredentials: false,
observe: 'events',
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment