提问者:小点点

(角8)文件或图片在转换为formdata时得到无效值(PS: formdata print Object Form{})


我遇到了从formdata获取无效值的问题。这个值在这个大小为5701的. fileData中是正确的,但是当它转换为表单数据时会得到无效值。当我控制台.log表单数据时它会变成{}。当我控制台.log(formdata[0])获取值未定义时。

代码我期望当formdata发布到后端时,文件是有效的。但是后端得到的是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: backend可以获取值ImmutableMultiDmit([('files', )]), 但是IDF.jpg的大小为0

ps2:控制台. log(formData.get('files'));显示如下文件

控制台. log(formData);显示如下FormData


共1个答案

匿名用户

_event.target将给出文件的内容

fileContent必须发送到服务器

  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'));
    }
  }

相关问题