我是Angular的初学者,我想知道如何创建Angular 5文件上传部分,我试图找到任何教程或文档,但我在任何地方都看不到任何东西。对此有什么想法吗?我尝试了ng4-files,但它不适用于Angular 5
当前回答
在Angular 7/8/9中
来源链接
使用自举表单
<form>
<div class="form-group">
<fieldset class="form-group">
<label>Upload Logo</label>
{{imageError}}
<div class="custom-file fileInputProfileWrap">
<input type="file" (change)="fileChangeEvent($event)" class="fileInputProfile">
<div class="img-space">
<ng-container *ngIf="isImageSaved; else elseTemplate">
<img [src]="cardImageBase64" />
</ng-container>
<ng-template #elseTemplate>
<img src="./../../assets/placeholder.png" class="img-responsive">
</ng-template>
</div>
</div>
</fieldset>
</div>
<a class="btn btn-danger" (click)="removeImage()" *ngIf="isImageSaved">Remove</a>
</form>
在组件类中
fileChangeEvent(fileInput: any) {
this.imageError = null;
if (fileInput.target.files && fileInput.target.files[0]) {
// Size Filter Bytes
const max_size = 20971520;
const allowed_types = ['image/png', 'image/jpeg'];
const max_height = 15200;
const max_width = 25600;
if (fileInput.target.files[0].size > max_size) {
this.imageError =
'Maximum size allowed is ' + max_size / 1000 + 'Mb';
return false;
}
if (!_.includes(allowed_types, fileInput.target.files[0].type)) {
this.imageError = 'Only Images are allowed ( JPG | PNG )';
return false;
}
const reader = new FileReader();
reader.onload = (e: any) => {
const image = new Image();
image.src = e.target.result;
image.onload = rs => {
const img_height = rs.currentTarget['height'];
const img_width = rs.currentTarget['width'];
console.log(img_height, img_width);
if (img_height > max_height && img_width > max_width) {
this.imageError =
'Maximum dimentions allowed ' +
max_height +
'*' +
max_width +
'px';
return false;
} else {
const imgBase64Path = e.target.result;
this.cardImageBase64 = imgBase64Path;
this.isImageSaved = true;
// this.previewImagePath = imgBase64Path;
}
};
};
reader.readAsDataURL(fileInput.target.files[0]);
}
}
removeImage() {
this.cardImageBase64 = null;
this.isImageSaved = false;
}
其他回答
在Angular 7/8/9中
来源链接
使用自举表单
<form>
<div class="form-group">
<fieldset class="form-group">
<label>Upload Logo</label>
{{imageError}}
<div class="custom-file fileInputProfileWrap">
<input type="file" (change)="fileChangeEvent($event)" class="fileInputProfile">
<div class="img-space">
<ng-container *ngIf="isImageSaved; else elseTemplate">
<img [src]="cardImageBase64" />
</ng-container>
<ng-template #elseTemplate>
<img src="./../../assets/placeholder.png" class="img-responsive">
</ng-template>
</div>
</div>
</fieldset>
</div>
<a class="btn btn-danger" (click)="removeImage()" *ngIf="isImageSaved">Remove</a>
</form>
在组件类中
fileChangeEvent(fileInput: any) {
this.imageError = null;
if (fileInput.target.files && fileInput.target.files[0]) {
// Size Filter Bytes
const max_size = 20971520;
const allowed_types = ['image/png', 'image/jpeg'];
const max_height = 15200;
const max_width = 25600;
if (fileInput.target.files[0].size > max_size) {
this.imageError =
'Maximum size allowed is ' + max_size / 1000 + 'Mb';
return false;
}
if (!_.includes(allowed_types, fileInput.target.files[0].type)) {
this.imageError = 'Only Images are allowed ( JPG | PNG )';
return false;
}
const reader = new FileReader();
reader.onload = (e: any) => {
const image = new Image();
image.src = e.target.result;
image.onload = rs => {
const img_height = rs.currentTarget['height'];
const img_width = rs.currentTarget['width'];
console.log(img_height, img_width);
if (img_height > max_height && img_width > max_width) {
this.imageError =
'Maximum dimentions allowed ' +
max_height +
'*' +
max_width +
'px';
return false;
} else {
const imgBase64Path = e.target.result;
this.cardImageBase64 = imgBase64Path;
this.isImageSaved = true;
// this.previewImagePath = imgBase64Path;
}
};
};
reader.readAsDataURL(fileInput.target.files[0]);
}
}
removeImage() {
this.cardImageBase64 = null;
this.isImageSaved = false;
}
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;
}
就我个人而言,我使用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'))
}
}
}
超文本标记语言
<div class="form-group">
<label for="file">Choose File</label><br /> <input type="file" id="file" (change)="uploadFiles($event.target.files)">
</div>
<button type="button" (click)="RequestUpload()">Ok</button>
ts文件
public formData = new FormData();
ReqJson: any = {};
uploadFiles( file ) {
console.log( 'file', file )
for ( let i = 0; i < file.length; i++ ) {
this.formData.append( "file", file[i], file[i]['name'] );
}
}
RequestUpload() {
this.ReqJson["patientId"] = "12"
this.ReqJson["requesterName"] = "test1"
this.ReqJson["requestDate"] = "1/1/2019"
this.ReqJson["location"] = "INDIA"
this.formData.append( 'Info', JSON.stringify( this.ReqJson ) )
this.http.post( '/Request', this.formData )
.subscribe(( ) => {
});
}
后端Spring(java文件)
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
@Controller
public class Request {
private static String UPLOADED_FOLDER = "c://temp//";
@PostMapping("/Request")
@ResponseBody
public String uploadFile(@RequestParam("file") MultipartFile file, @RequestParam("Info") String Info) {
System.out.println("Json is" + Info);
if (file.isEmpty()) {
return "No file attached";
}
try {
// Get the file and save it somewhere
byte[] bytes = file.getBytes();
Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename());
Files.write(path, bytes);
} catch (IOException e) {
e.printStackTrace();
}
return "Succuss";
}
}
我们必须在C驱动器中创建一个文件夹“temp”,然后这段代码将在控制台中打印Json并将上传的文件保存在创建的文件夹中
首先,你需要在你的Angular项目中设置HttpClient。
打开src/app/app.module。导入HttpClientModule并将其添加到模块的imports数组中,如下所示:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HttpClientModule } from '@angular/common/http';
@NgModule({
declarations: [
AppComponent,
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
接下来,生成一个组件:
$ ng generate component home
接下来,生成一个上传服务:
$ ng generate service upload
接下来,打开src/app/upload.service。Ts文件如下:
import { HttpClient, HttpEvent, HttpErrorResponse, HttpEventType } from '@angular/common/http';
import { map } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class UploadService {
SERVER_URL: string = "https://file.io/";
constructor(private httpClient: HttpClient) { }
public upload(formData) {
return this.httpClient.post<any>(this.SERVER_URL, formData, {
reportProgress: true,
observe: 'events'
});
}
}
接下来,打开src/app/home/home.component.ts文件,开始添加以下导入:
import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { HttpEventType, HttpErrorResponse } from '@angular/common/http';
import { of } from 'rxjs';
import { catchError, map } from 'rxjs/operators';
import { UploadService } from '../upload.service';
接下来,定义fileUpload和files变量,并注入UploadService,如下所示:
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
@ViewChild("fileUpload", {static: false}) fileUpload: ElementRef;files = [];
constructor(private uploadService: UploadService) { }
接下来,定义uploadFile()方法:
uploadFile(file) {
const formData = new FormData();
formData.append('file', file.data);
file.inProgress = true;
this.uploadService.upload(formData).pipe(
map(event => {
switch (event.type) {
case HttpEventType.UploadProgress:
file.progress = Math.round(event.loaded * 100 / event.total);
break;
case HttpEventType.Response:
return event;
}
}),
catchError((error: HttpErrorResponse) => {
file.inProgress = false;
return of(`${file.data.name} upload failed.`);
})).subscribe((event: any) => {
if (typeof (event) === 'object') {
console.log(event.body);
}
});
}
接下来,定义uploadFiles()方法,该方法可用于上传多个图像文件:
private uploadFiles() {
this.fileUpload.nativeElement.value = '';
this.files.forEach(file => {
this.uploadFile(file);
});
}
接下来,定义onClick()方法:
onClick() {
const fileUpload = this.fileUpload.nativeElement;fileUpload.onchange = () => {
for (let index = 0; index < fileUpload.files.length; index++)
{
const file = fileUpload.files[index];
this.files.push({ data: file, inProgress: false, progress: 0});
}
this.uploadFiles();
};
fileUpload.click();
}
接下来,我们需要创建图像上传UI的HTML模板。打开src/app/home/home.component.html文件,添加以下内容:
<div [ngStyle]="{'text-align':center; 'margin-top': 100px;}">
<button mat-button color="primary" (click)="fileUpload.click()">choose file</button>
<button mat-button color="warn" (click)="onClick()">Upload</button>
<input [hidden]="true" type="file" #fileUpload id="fileUpload" name="fileUpload" multiple="multiple" accept="image/*" />
</div>
看看这篇教程和这篇文章
推荐文章
- 运行单个测试文件
- “declare”在“export declare class Actions”中做什么?
- NG6002:出现在NgModule中。导入AppModule类,但不能解析为NgModule类
- 向Angular HttpClient添加一个HTTP头并不会发送这个头,为什么?
- 不能绑定到'ngForOf',因为它不是'tr'的已知属性(最终版本)
- Angular中的全局事件
- Angular和Typescript:不能找到名字——错误:不能找到名字
- HttpModule和HttpClientModule的区别
- 禁用响应式输入字段
- 'this'隐式具有类型'any',因为它没有类型注释
- 带有用户单击所选组件的动态选项卡
- 在TypeScript中声明抽象方法
- 如何强制tsc忽略node_modules文件夹?
- TypeScript for…的索引/键?
- 如何在Typescript中获得一个变量类型?