我是Angular的初学者,我想知道如何创建Angular 5 File upload部分,我尝试查找任何教程或文档,但是在任何地方都看不到任何东西。有什么想法吗?我正在尝试ng4-文件,但不适用于Angular 5
我是Angular的初学者,我想知道如何创建Angular 5 File upload部分,我尝试查找任何教程或文档,但是在任何地方都看不到任何东西。有什么想法吗?我正在尝试ng4-文件,但不适用于Angular 5
Answers:
这是一个将文件上传到api的工作示例:
步骤1:HTML模板(file-upload.component.html)
定义类型的简单输入标签file
。向(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(file-upload.component.ts)中上传处理
为所选文件定义默认变量。
fileToUpload: File = 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);
});
}
步骤3:文件上传服务(file-upload.service.ts)
通过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));
}
因此,这是一个非常简单的工作示例,我每天在工作中都会使用它。
const invFormData: FormData = new FormData(); invFormData.append('invoiceAttachment', invoiceAttachment, invoiceAttachment.name); invFormData.append('invoiceInfo', JSON.stringify(invoiceInfo));
控制器具有两个对应的参数,但是我必须在控制器中解析JSON。我的Core 2控制器不会自动在参数中提取模型。我的原始设计是带有文件属性的模型,但我无法使它正常工作
createContrat(fileToUpload: File, newContrat: Contrat): Observable<boolean> { let headers = new Headers(); const endpoint = Api.getUrl(Api.URLS.createContrat)); const formData: FormData =new FormData(); formData.append('fileKey', fileToUpload, FileToUpload.name); let body newContrat.gup(this.auth.getCurrentUser().token); return this.http .post(endpoint, formData, body) .map(() => { return true; }) }
Content-Disposition: form-data; name="fileKey"; filename="file.docx" Content-Type: application/octet-stream <file>
这样,我将上传文件实施到项目中的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.NET Web API
[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);
}
非常简单快捷的方法是使用ng2-file-upload。
通过npm安装ng2-file-upload。 npm i ng2-file-upload --save
首先,在模块中导入模块。
import { FileUploadModule } from 'ng2-file-upload';
Add it to [imports] under @NgModule:
imports: [ ... FileUploadModule, ... ]
标记:
<input ng2FileSelect type="file" accept=".xml" [uploader]="uploader"/>
在您的ts中:
import { FileUploader } from 'ng2-file-upload';
...
uploader: FileUploader = new FileUploader({ url: "api/your_upload", removeAfterUpload: false, autoUpload: true });
这是最简单的用法。要了解所有功能,请参阅演示
我使用的是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
好的,因为该线程出现在google的第一个结果中,对于其他有相同问题的用户,您不必像trueboroda所指出的那样重新设计轮子,就可以使用ng2-file-upload库,该库简化了上传角度为6和7的文件,您需要做的是:
安装最新的Angular CLI
yarn add global @angular/cli
然后安装rx-compat以解决兼容性问题
npm install rxjs-compat --save
安装ng2-file-upload
npm install ng2-file-upload --save
在模块中导入FileSelectDirective指令。
import { FileSelectDirective } from 'ng2-file-upload';
Add it to [declarations] under @NgModule:
declarations: [ ... FileSelectDirective , ... ]
在你的组件中
import { FileUploader } from 'ng2-file-upload/ng2-file-upload';
...
export class AppComponent implements OnInit {
public uploader: FileUploader = new FileUploader({url: URL, itemAlias: 'photo'});
}
模板
<input type="file" name="photo" ng2FileSelect [uploader]="uploader" />
为了更好地理解,您可以检查以下链接: 如何使用Angular 6/7上传文件
我个人是使用ngx-material-file-input作为前端,使用Firebase作为后端来进行此操作。更精确地说,是将Cloud Firestore与后端的Firebase C Loud Storage for Backbase结合使用。下面的示例将文件限制为不大于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>
contact.component.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)
])
]
})
contact.component.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();
}
}
储存规则
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'))
}
}
}
toString()
contactForm声明?
toString()
没用,编辑了我的答案。对于那些会阅读此评论的人,我fileUploader
在contact.component.ts的结尾处有])].toString()})
。现在,它只是:])]})
。
<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>
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(( ) => {
});
}
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.ts文件,导入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();
}
接下来,我们需要创建图像上传用户界面的HTML模板。打开src / app / home / home.component.html文件并添加以下内容:
<div style="text-align:center; margin-top: 100px; ">
<button mat-button color="warn" (click)="onClick()">
Upload
</button>
<input type="file" #fileUpload id="fileUpload" name="fileUpload" multiple="multiple" accept="image/*" style="display:none;" /></div>
使用Angular和Node.js上载文件的完整示例(快速)
HTML代码
<div class="form-group">
<label for="file">Choose File</label><br/>
<input type="file" id="file" (change)="uploadFile($event.target.files)" multiple>
</div>
TS组件代码
uploadFile(files) {
console.log('files', files)
var formData = new FormData();
for(let i =0; i < files.length; i++){
formData.append("files", files[i], files[i]['name']);
}
this.httpService.httpPost('/fileUpload', formData)
.subscribe((response) => {
console.log('response', response)
},
(error) => {
console.log('error in fileupload', error)
})
}
节点Js代码
fileUpload API控制器
function start(req, res) {
fileUploadService.fileUpload(req, res)
.then(fileUploadServiceResponse => {
res.status(200).send(fileUploadServiceResponse)
})
.catch(error => {
res.status(400).send(error)
})
}
module.exports.start = start
使用multer上载服务
const multer = require('multer') // import library
const moment = require('moment')
const q = require('q')
const _ = require('underscore')
const fs = require('fs')
const dir = './public'
/** Store file on local folder */
let storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'public')
},
filename: function (req, file, cb) {
let date = moment(moment.now()).format('YYYYMMDDHHMMSS')
cb(null, date + '_' + file.originalname.replace(/-/g, '_').replace(/ /g, '_'))
}
})
/** Upload files */
let upload = multer({ storage: storage }).array('files')
/** Exports fileUpload function */
module.exports = {
fileUpload: function (req, res) {
let deferred = q.defer()
/** Create dir if not exist */
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir)
console.log(`\n\n ${dir} dose not exist, hence created \n\n`)
}
upload(req, res, function (err) {
if (req && (_.isEmpty(req.files))) {
deferred.resolve({ status: 200, message: 'File not attached', data: [] })
} else {
if (err) {
deferred.reject({ status: 400, message: 'error', data: err })
} else {
deferred.resolve({
status: 200,
message: 'File attached',
filename: _.pluck(req.files,
'filename'),
data: req.files
})
}
}
})
return deferred.promise
}
}
试试这个
安装
npm install primeng --save
进口
import {FileUploadModule} from 'primeng/primeng';
HTML
<p-fileUpload name="myfile[]" url="./upload.php" multiple="multiple"
accept="image/*" auto="auto"></p-fileUpload>
在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;
}
Choose File
btn上传?在这两种情况下,您只需使用FormData