问题
when I'm trying to install "npm install ng2-file-upload --save" in my angular 4 application it throws
UNMET PEER DEPENDENCY @4.1.0
UNMET PEER DEPENDENCY @4.1.0
`-- ng2-file-upload@1.2.1
and upload is not working my applications throws
"Can't bind to 'uploader' since it isn't a known property of 'input'"
this is my HTML
<input type="file" ng2FileSelect [uploader]="upload" multiple formControlName="file" id="file"/>
and its Component
import { FileUploadModule } from 'ng2-file-upload/ng2-file-upload';
import { FileSelectDirective, FileUploader } from 'ng2-file-upload/ng2-file-
upload';
export class PersonalInfoComponent implements OnInit
{
public upload:FileUploader= new FileUploader({url:""});
}
Parent Module
import { FileUploadModule } from 'ng2-file-upload/ng2-file-upload';
@NgModule({
imports: [
..
....
..
FileUploadModule
],
export class RegistrationModule { }
and I didn't Import/change anything in AppModule(Grand Parent Module).
can someone help me on this please...
回答1:
Upload images in Angular 4 without a plugin This is the article that might be worth trying. Upload images in Angular 4 without a plugin
It emphasize on these points:
- Using the .request() method instead of .post
- Sending formData straight into the body.
- Customizing header items and constructing a new RequestOptions object.
- In order to send formData with image content you must remove the Content-Type header.
回答2:
I don't think we need some extra libraries
onFileChange(event){
let files = event.target.files;
this.saveFiles(files);
}
@HostListener('dragover', ['$event']) onDragOver(event) {
this.dragAreaClass = "droparea";
event.preventDefault();
}
@HostListener('dragenter', ['$event']) onDragEnter(event) {
this.dragAreaClass = "droparea";
event.preventDefault();
}
@HostListener('dragend', ['$event']) onDragEnd(event) {
this.dragAreaClass = "dragarea";
event.preventDefault();
}
@HostListener('dragleave', ['$event']) onDragLeave(event) {
this.dragAreaClass = "dragarea";
event.preventDefault();
}
@HostListener('drop', ['$event']) onDrop(event) {
this.dragAreaClass = "dragarea";
event.preventDefault();
event.stopPropagation();
var files = event.dataTransfer.files;
this.saveFiles(files);
}
And now we are ready to upload files with drag and drop as well as by clicking the link button and upload extra data with files.
See the complete article here Angular 4 upload files with data and web api by drag & drop
回答3:
For common solution is to create new module like shared module
. You just need create shared module like
this and import shared module in app.module
file
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { FileSelectDirective, FileDropDirective } from 'ng2-file-upload';
import { FileUploadModule } from 'ng2-file-upload/ng2-file-upload';
@NgModule({
imports: [ FileUploadModule],
declarations: [ ],
exports :[ FileSelectDirective, FileDropDirective, FormsModule,
FileUploadModule],
})
export class SharedModule { }
just import share.module in your app.module like this.
import { NgModule } from '@angular/core';
import { SharedModule} from '../shared/shared.module';
@NgModule({
imports: [SharedModule],
declarations: [],
exports :[],
})
export class AppModule { }
take a look on lazy loading in angular 4
回答4:
You don't need an external library to do this, check below sample code
@Component({
selector: 'app-root',
template: '<div>'
+ '<input type="file" (change)="upload($event)">'
+ '</div>',
})
export class AppComponent {
constructor(private _service: commonService) { }
upload(event: any) {
let files = event.target.files;
let fData: FormData = new FormData;
for (var i = 0; i < files.length; i++) {
fData.append("file[]", files[i]);
}
var _data = {
filename: 'Sample File',
id: '0001'
}
fData.append("data", JSON.stringify(_data));
this._service.uploadFile(fData).subscribe(
response => this.handleResponse(response),
error => this.handleError(error)
)
}
handleResponse(response: any) {
console.log(response);
}
handleError(error: string) {
console.log(error);
}
}
More info
回答5:
HTML:
<input type="file" (change)="onFileChange($event)" id="file">
TS:
@Component({
......
})
export class myComponent{
form: FormGroup;
contructor(fb: FormGroup){
form: fb.group({file: null});
}
//fVals comes from HTML Form -> (ngSubmit)="postImage(form.value)"
postImage(fVals){
let body = new FormData();
body.append('file', formValues.file);
let httpRequest = httpclient.post(url, body);
httpRequest.subscribe((response) =>{
//..... handle response here
},(error) => {
//.....handle errors here
});
}
onFileChange(event) {
if(event.target.files.length > 0) {
let file = event.target.files[0];
this.form.get('file').setValue(file);
}
}
}
回答6:
import fileupload from primeng or use simple file uploader
HTML
<p-fileUpload name="myfile[]" customUpload="true"
(uploadHandler)="uploadSuiteForRelease($event)" auto="auto"></p-fileUpload>
TS
var data = new FormData();
let index: number = 0;
if (this.files != undefined)
{
for (let file of this.files.files)
{
data.append("myFile" + index, file);
++index;
}
}
data.append('viewModel', JSON.stringify(<<data model that needs to be
sent with request>>));
Send this data with request return this._httpClient.post('api/controller', data);
Server
[HttpPost]
public async Task<IHttpActionResult> Post()
{
HttpPostedFile httpPostedFile = null;
var viewModel = JsonConvert.DeserializeObject<ReleasesViewModel>(HttpContext.Current.Request["viewModel"]);
if (viewModel != null)
{
if (HttpContext.Current.Request.Files.AllKeys.Any())
{
var cnt = HttpContext.Current.Request.Files.Count;
for (int i = 0; i < cnt; i++)
{
httpPostedFile = HttpContext.Current.Request.Files["myFile" + i];
}
}
}
}
来源:https://stackoverflow.com/questions/43993145/file-upload-in-angular-4