(angular 8) 文件或图片在转换为 formdata 时得到无效值 (PS: formdata print Object Form{})
(angular 8) file or picture got invalid value while converted to formdata (PS: formdata print Object Form{})
我遇到了从表单数据获取无效值的问题。该值在 this.fileData 中是正确的,大小为 5701,但在转换为表单数据时得到无效值。当我 console.log 时它变成了 {}
表格数据。当我 console.log(formdata[0]) 得到未定义的值时。
我期望的代码是当formdata post到后端时,文件是有效的。但是后端得到的是 0 尺寸的图片。我猜问题出在 formdata 上,因为 formdata 什么也得不到。
关于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>
关于打字稿
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(){}
}
这里是 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:
后端可以获得值ImmutableMultiDict([('files', )]),但是IDF.jpg是0大小
ps2:
console.log(formData.get('files'));显示如下
文件 {name: "IDF.jpg", lastModified: 1574402253947, lastModifiedDate: Fri Nov 22 2019 13:57:33 GMT+0800 (), webkitRelativePath: "", size: 5701, ...}
console.log(表格数据);显示如下
表单数据{}
_event.target.result 将给出文件的内容
必须将文件内容发送到服务器
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'));
}
}
我遇到了从表单数据获取无效值的问题。该值在 this.fileData 中是正确的,大小为 5701,但在转换为表单数据时得到无效值。当我 console.log 时它变成了 {} 表格数据。当我 console.log(formdata[0]) 得到未定义的值时。
我期望的代码是当formdata post到后端时,文件是有效的。但是后端得到的是 0 尺寸的图片。我猜问题出在 formdata 上,因为 formdata 什么也得不到。
关于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>
关于打字稿
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(){}
}
这里是 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: 后端可以获得值ImmutableMultiDict([('files', )]),但是IDF.jpg是0大小
ps2: console.log(formData.get('files'));显示如下 文件 {name: "IDF.jpg", lastModified: 1574402253947, lastModifiedDate: Fri Nov 22 2019 13:57:33 GMT+0800 (), webkitRelativePath: "", size: 5701, ...}
console.log(表格数据);显示如下 表单数据{}
_event.target.result 将给出文件的内容
必须将文件内容发送到服务器
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'));
}
}