I got the problem for getting invalid value from formdata. The value is correct in this.fileData with size 5701, but get invalid value when it convert to form data. It becomes {} when I console.log form data. When I console.log(formdata[0]) getting value undefined.
The code I expect that when the formdata post to backend, the file is valid. But backend gets the 0 size picture. I guess that the problem is from formdata, because formdata gets nothing.
about html
<div class="container">
<div class="row">
<div class="col-md-6 offset-md-3">
<h3>Choose File</h3>
<div class="form-group">
<input type="file" name="image" (change)="fileProgress($event)" />
</div>
<div *ngIf="fileUploadProgress">
Upload progress: {{ fileUploadProgress }}
</div>
<div class="image-preview mb-3" *ngIf="previewUrl">
<img [src]="previewUrl" height="300" />
</div>
<div class="mb-3" *ngIf="uploadedFilePath">
{{uploadedFilePath}}
</div>
<div class="form-group">
<button class="btn btn-primary" (click)="onSubmit()">Submit</button>
</div>
</div>
</div>
</div>
about typescripts
import { Component, OnInit, Input } from '@angular/core';
import { HttpClient, HttpEventType } from '@angular/common/http';
import { UploadService } from '../../../model/shared/api/upload.service';
import { HttpHeaders } from '@angular/common/http';
import { LoginComponent } from '../../account/auth/login/login.component';
import { HttpClientModule } from '@angular/common/http';
//import * as myGlobals from './globals';
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
//'Authorization': 'my-auth-token'
})
};
@Component({
selector: 'cd-upload',
templateUrl: './upload.component.html',
styleUrls: ['./upload.component.scss']
})
export class UploadComponent implements OnInit{
fileData: File = null;
previewUrl:any = null;
fileUploadProgress: string = null;
uploadedFilePath: string = null;
constructor(private uploadService: UploadService,private httpClient: HttpClient,private http: HttpClient) {
}
fileProgress(fileInput: any) {
this.fileData = <File>fileInput.target.files[0];
this.preview();
}
preview() {
// Show preview
var mimeType = this.fileData.type;
if (mimeType.match(/image\/*/) == null) {
return;
}
var reader = new FileReader();
reader.readAsDataURL(this.fileData);
reader.onload = (_event) => {
this.previewUrl = reader.result;
}
}
onSubmit() {
//here is the problem
const formData = new FormData();
formData.append('files', this.fileData);
console.log(this.fileData);
console.log(formData[0]);
console.log(formData);
this.http.post('http://api', formData, {
reportProgress: true,responseType: 'blob' as 'json',
observe: 'events'
})
//here is the problem
}
ngOnInit(){}
}
here is the backend code with python FLask
@app.route('/bupload', methods=['GET', 'POST'])
def bupload():
result="Upload done";result1="Upload fail";result2="File not allowed";result3="No selected file";result4="No file part";form="123";
print(request.files); print(request.files['files']);#request.files=ImmutableMultiDict(request.files).to_dict(flat=False);print(request.files['file']);
#upload_First(form, request.files['files'])
if 'files' not in request.files:
flash('No file part');print(file);
return result4
file = request.files['files'];print(file);print("@0");
# if user does not select file, browser also
# submit a empty part without filename
if file.filename == '':
flash('No selected file')
return result3
if file and allowed_file(file.filename):
if(upload_First(form, file)):
flash('Upload done');
print("@");
return result
else:
flash('Upload fail')
return result1
else:
flash('File not allowed')
return result2
ps: backend can get the value ImmutableMultiDict([('files', )]), but the IDF.jpg is 0 size
ps2: console.log(formData.get('files')); show as below File {name: "IDF.jpg", lastModified: 1574402253947, lastModifiedDate: Fri Nov 22 2019 13:57:33 GMT+0800 (), webkitRelativePath: "", size: 5701, …}
console.log(formData); show as below FormData {}
_event.target.result will give the content of file
fileContent has to be sent to server
fileProgress(fileInput){
var file = <File>fileInput.target.files[0];
const formData = new FormData();
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = (_event) => {
formData.append('photo', _event.target.result);
console.log(formData.get('photo'));
}
}