我是Angular的初学者,我想知道如何创建Angular 5文件上传部分,我试图找到任何教程或文档,但我在任何地方都看不到任何东西。对此有什么想法吗?我尝试了ng4-files,但它不适用于Angular 5
当前回答
在我的情况下,我使用http拦截器,事情是,默认情况下,我的http拦截器设置内容类型头为应用程序/json,但对于文件上传,我使用multer库。 稍微改变一下我的http。interceptor定义,如果请求体是FormData,它会删除头,不触及访问令牌。 下面是一部分代码,它让我很开心。
if (request.body instanceof FormData) {
request = request.clone({ headers: request.headers.delete('Content-Type', 'application/json') });
}
if (request.body instanceof FormData) {
request = request.clone({ headers: request.headers.delete('Accept', 'application/json')});
}
其他回答
下面是一个上传文件到api的例子:
步骤1:HTML模板
定义文件类型的简单输入标记。为(change)-event添加一个处理选择文件的函数。
<div class="form-group">
<label for="file">Choose File</label>
<input type="file"
id="file"
(change)="handleFileInput($event.target.files)">
</div>
步骤2:在TypeScript中处理上传
为所选文件定义一个默认变量。
fileToUpload: File | null = null;
创建你在(change)-event中使用的函数:
handleFileInput(files: FileList) {
this.fileToUpload = files.item(0);
}
如果你想处理多文件选择,那么你可以遍历这个文件数组。
现在通过调用file-upload.service创建文件上传函数:
uploadFileToActivity() {
this.fileUploadService.postFile(this.fileToUpload).subscribe(data => {
// do something, if upload success
}, error => {
console.log(error);
});
}
第三步:文件上传服务
通过post方法上传文件,你应该使用FormData,因为这样你可以添加文件到http请求。
postFile(fileToUpload: File): Observable<boolean> {
const endpoint = 'your-destination-url';
const formData: FormData = new FormData();
formData.append('fileKey', fileToUpload, fileToUpload.name);
return this.httpClient
.post(endpoint, formData, { headers: yourHeadersConfig })
.map(() => { return true; })
.catch((e) => this.handleError(e));
}
所以,这是一个非常简单的工作例子,我每天都在工作中使用。
通过这种方式,我实现了在项目中上传文件到web API。
我为谁分担关心。
const formData: FormData = new FormData();
formData.append('Image', image, image.name);
formData.append('ComponentId', componentId);
return this.http.post('/api/dashboard/UploadImage', formData);
一步一步
ASP。网上广告
[HttpPost]
[Route("api/dashboard/UploadImage")]
public HttpResponseMessage UploadImage()
{
string imageName = null;
var httpRequest = HttpContext.Current.Request;
//Upload Image
var postedFile = httpRequest.Files["Image"];
//Create custom filename
if (postedFile != null)
{
imageName = new String(Path.GetFileNameWithoutExtension(postedFile.FileName).Take(10).ToArray()).Replace(" ", "-");
imageName = imageName + DateTime.Now.ToString("yymmssfff") + Path.GetExtension(postedFile.FileName);
var filePath = HttpContext.Current.Server.MapPath("~/Images/" + imageName);
postedFile.SaveAs(filePath);
}
}
HTML表单
<form #imageForm=ngForm (ngSubmit)="OnSubmit(Image)">
<img [src]="imageUrl" class="imgArea">
<div class="image-upload">
<label for="file-input">
<img src="upload.jpg" />
</label>
<input id="file-input" #Image type="file" (change)="handleFileInput($event.target.files)" />
<button type="submit" class="btn-large btn-submit" [disabled]="Image.value=='' || !imageForm.valid"><i
class="material-icons">save</i></button>
</div>
</form>
TS文件使用API
OnSubmit(Image) {
this.dashboardService.uploadImage(this.componentId, this.fileToUpload).subscribe(
data => {
console.log('done');
Image.value = null;
this.imageUrl = "/assets/img/logo.png";
}
);
}
服务TS
uploadImage(componentId, image) {
const formData: FormData = new FormData();
formData.append('Image', image, image.name);
formData.append('ComponentId', componentId);
return this.http.post('/api/dashboard/UploadImage', formData);
}
我使用的是Angular 5.2.11, 我喜欢Gregor Doroschenko提供的解决方案,但是我注意到上传的文件是零字节的,我必须做一个小小的改变才能让它为我工作。
postFile(fileToUpload: File): Observable<boolean> {
const endpoint = 'your-destination-url';
return this.httpClient
.post(endpoint, fileToUpload, { headers: yourHeadersConfig })
.map(() => { return true; })
.catch((e) => this.handleError(e));
}
下面几行(formData)对我不起作用。
const formData: FormData = new FormData();
formData.append('fileKey', fileToUpload, fileToUpload.name);
https://github.com/amitrke/ngrke/blob/master/src/app/services/fileupload.service.ts
就我个人而言,我使用ngx-material-file-input作为前端,Firebase作为后端。更准确地说,后端是与Cloud Firestore结合的Cloud Storage for Firebase。下面是一个示例,它限制文件不大于20 MB,并且只接受某些文件扩展名。我还使用Cloud Firestore来存储上传文件的链接,但你可以跳过这个。
contact.component.html
<mat-form-field>
<!--
Accept only files in the following format: .doc, .docx, .jpg, .jpeg, .pdf, .png, .xls, .xlsx. However, this is easy to bypass, Cloud Storage rules has been set up on the back-end side.
-->
<ngx-mat-file-input
[accept]="[
'.doc',
'.docx',
'.jpg',
'.jpeg',
'.pdf',
'.png',
'.xls',
'.xlsx'
]"
(change)="uploadFile($event)"
formControlName="fileUploader"
multiple
aria-label="Here you can add additional files about your project, which can be helpeful for us."
placeholder="Additional files"
title="Additional files"
type="file"
>
</ngx-mat-file-input>
<mat-icon matSuffix>folder</mat-icon>
<mat-hint
>Accepted formats: DOC, DOCX, JPG, JPEG, PDF, PNG, XLS and XLSX,
maximum files upload size: 20 MB.
</mat-hint>
<!--
Non-null assertion operators are required to let know the compiler that this value is not empty and exists.
-->
<mat-error
*ngIf="contactForm.get('fileUploader')!.hasError('maxContentSize')"
>
This size is too large,
<strong
>maximum acceptable upload size is
{{
contactForm.get('fileUploader')?.getError('maxContentSize')
.maxSize | byteFormat
}}</strong
>
(uploaded size:
{{
contactForm.get('fileUploader')?.getError('maxContentSize')
.actualSize | byteFormat
}}).
</mat-error>
</mat-form-field>
ts(大小验证器部分)
import { FileValidator } from 'ngx-material-file-input';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
/**
* @constructor
* @description Creates a new instance of this component.
* @param {formBuilder} - an abstraction class object to create a form group control for the contact form.
*/
constructor(
private angularFirestore: AngularFirestore,
private angularFireStorage: AngularFireStorage,
private formBuilder: FormBuilder
) {}
public maxFileSize = 20971520;
public contactForm: FormGroup = this.formBuilder.group({
fileUploader: [
'',
Validators.compose([
FileValidator.maxContentSize(this.maxFileSize),
Validators.maxLength(512),
Validators.minLength(2)
])
]
})
ts(文件上传器部分)
import { AngularFirestore } from '@angular/fire/firestore';
import {
AngularFireStorage,
AngularFireStorageReference,
AngularFireUploadTask
} from '@angular/fire/storage';
import { catchError, finalize } from 'rxjs/operators';
import { throwError } from 'rxjs';
public downloadURL: string[] = [];
/**
* @description Upload additional files to Cloud Firestore and get URL to the files.
* @param {event} - object of sent files.
* @returns {void}
*/
public uploadFile(event: any): void {
// Iterate through all uploaded files.
for (let i = 0; i < event.target.files.length; i++) {
const randomId = Math.random()
.toString(36)
.substring(2); // Create random ID, so the same file names can be uploaded to Cloud Firestore.
const file = event.target.files[i]; // Get each uploaded file.
// Get file reference.
const fileRef: AngularFireStorageReference = this.angularFireStorage.ref(
randomId
);
// Create upload task.
const task: AngularFireUploadTask = this.angularFireStorage.upload(
randomId,
file
);
// Upload file to Cloud Firestore.
task
.snapshotChanges()
.pipe(
finalize(() => {
fileRef.getDownloadURL().subscribe((downloadURL: string) => {
this.angularFirestore
.collection(process.env.FIRESTORE_COLLECTION_FILES!) // Non-null assertion operator is required to let know the compiler that this value is not empty and exists.
.add({ downloadURL: downloadURL });
this.downloadURL.push(downloadURL);
});
}),
catchError((error: any) => {
return throwError(error);
})
)
.subscribe();
}
}
storage.rules
rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read; // Required in order to send this as attachment.
// Allow write files Firebase Storage, only if:
// 1) File is no more than 20MB
// 2) Content type is in one of the following formats: .doc, .docx, .jpg, .jpeg, .pdf, .png, .xls, .xlsx.
allow write: if request.resource.size <= 20 * 1024 * 1024
&& (request.resource.contentType.matches('application/msword')
|| request.resource.contentType.matches('application/vnd.openxmlformats-officedocument.wordprocessingml.document')
|| request.resource.contentType.matches('image/jpg')
|| request.resource.contentType.matches('image/jpeg')
|| request.resource.contentType.matches('application/pdf')
|| request.resource.contentType.matches('image/png')
|| request.resource.contentType.matches('application/vnd.ms-excel')
|| request.resource.contentType.matches('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'))
}
}
}
create-profile.html
<body>
<h1 class="font-weight-bold" >Create Advertistment</h1>
<hr />
<form [formGroup]="form" (submit)="onSubmit()">
<div>
<label class="font-weight-bold">Insert Subject name</label>
<br>
<input formControlName="name" type="text" placeholder="Enter name..." />
</div>
<div>
<br>
<label class="font-weight-bold">Select the Advertistment</label>
<br>
<input (change)="onFileSelect($event)" type="file" />
</div>
<br>
<!--<div *ngIf="imageData">
<img [src]="imageData" [alt]="form.value.name" />
</div>-->
<div>
<label class="font-weight-bold">Upload the Advertistment</label>
<br>
<button type="submit" class="btn btn-success" >Upload Advertistment</button>
</div>
</form>
</body>
create-profile.ts
import { Component, OnInit } from "@angular/core";
import { FormGroup, FormControl } from "@angular/forms";
import { Profile } from "../../models/Profile";
import { ProfileService } from "src/app/services/profile.service";
@Component({
selector: "app-create-profile",
templateUrl: "./create-profile.component.html",
styleUrls: ["./create-profile.component.css"],
})
export class CreateProfileComponent implements OnInit {
form: FormGroup;
profile: Profile;
imageData: string;
constructor(private profileService: ProfileService) {}
ngOnInit(): void {
this.form = new FormGroup({
name: new FormControl(null),
image: new FormControl(null),
});
}
onFileSelect(event: Event) {
const file = (event.target as HTMLInputElement).files[0];
this.form.patchValue({ image: file });
const allowedMimeTypes = ["image/png", "image/jpeg", "image/jpg"];
if (file && allowedMimeTypes.includes(file.type)) {
const reader = new FileReader();
reader.onload = () => {
this.imageData = reader.result as string;
};
reader.readAsDataURL(file);
}
}
onSubmit() {
this.profileService.addProfile(this.form.value.name, this.form.value.image);
this.form.reset();
this.imageData = null;
}
}
profile.service.ts
import { Injectable } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { map } from "rxjs/operators";
import { Profile } from "../models/Profile";
import { Subject } from "rxjs";
@Injectable({
providedIn: "root",
})
export class ProfileService {
private profiles: Profile[] = [];
private profiles$ = new Subject<Profile[]>();
readonly url = "http://localhost:3000/api/profiles";
constructor(private http: HttpClient) {}
getProfiles() {
this.http
.get<{ profiles: Profile[] }>(this.url)
.pipe(
map((profileData) => {
return profileData.profiles;
})
)
.subscribe((profiles) => {
this.profiles = profiles;
this.profiles$.next(this.profiles);
});
}
getProfilesStream() {
return this.profiles$.asObservable();
}
addProfile(name: string, image: File): void {
const profileData = new FormData();
profileData.append("name", name);
profileData.append("image", image, name);
this.http
.post<{ profile: Profile }>(this.url, profileData)
.subscribe((profileData) => {
const profile: Profile = {
_id: profileData.profile._id,
name: name,
imagePath: profileData.profile.imagePath,
};
this.profiles.push(profile);
this.profiles$.next(this.profiles);
});
}
}
Profile.ts
export interface Profile {
_id: string;
name: string;
imagePath: string;
}
推荐文章
- 如何在Typescript中解析JSON字符串
- TypeScript中的extends和implements有什么区别
- 如何用angular 2路由器重新加载当前路由
- 创建组件与Angular-CLI &将它添加到一个特定的模块
- 迭代Typescript Map
- 定义TypeScript回调类型
- @HostBinding和@HostListener:它们是做什么用的?
- 如何在TypeScript中实现睡眠函数?
- 在Angular 6中生成服务时,为din提供可注入装饰器的目的是什么?
- 返回一个空的Observable
- 为什么——isolatedModules错误被任何导入修复?
- 如何用npm更新TypeScript到最新版本?
- 如何在angular2中调用另一个组件函数
- Angular 2可选的路由参数
- Typescript:在类型“{" a ":字符串上找不到参数类型为'string'的索引签名;}