Angular 文件上传

336

我是Angular的新手,想知道如何创建Angular 5文件上传部分,我在尝试寻找任何教程或文档,但是无论在哪里都没有看到。有什么建议吗?我尝试过ng4-files,但它不适用于Angular 5。


4
你想使用拖放功能还是简单的“选择文件”按钮上传?不管哪种情况,你都可以使用FormData来上传。 - Dhyey
4
请看一下primeng,我已经使用它有一段时间了,它可以与Angular v5兼容。https://www.primefaces.org/primeng/#/fileupload - Bunyamin Coskuner
如果您只需要将JSON上传到客户端,请查看以下问题: https://dev59.com/_7Lma4cB1Zd3GeqPX0Cf - AnthonyW
15个回答

658

以下是上传文件到API的工作示例:

第1步:HTML模板(file-upload.component.html)

定义一个简单的输入标签,类型为file。 添加一个函数来处理选择文件的(change)事件。

<div class="form-group">
    <label for="file">Choose File</label>
    <input type="file"
           id="file"
           (change)="handleFileInput($event.target.files)">
</div>

第二步:在 TypeScript 中处理上传(file-upload.component.ts)

定义一个默认变量来选择文件。

fileToUpload: File | null = null;

创建一个函数,你可以在文件输入标签的 (change) 事件中使用它:
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);
      });
  }

第三步:文件上传服务(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));
}

所以,这是一个非常简单的工作示例,我在我的工作中每天都使用它。


2
@GregorDoroschenko 我试图使用一个包含有关文件的附加信息的模型,并且我不得不这样做才能使它工作: const invFormData: FormData = new FormData(); invFormData.append('invoiceAttachment', invoiceAttachment, invoiceAttachment.name); invFormData.append('invoiceInfo', JSON.stringify(invoiceInfo));控制器有两个相应的参数,但我不得不在控制器中解析JSON。我的Core 2控制器无法自动获取参数中的模型。我的原始设计是一个带有文件属性的模型,但我无法使其工作。 - Papa Stahl
2
使用 Angular 5,这个不起作用。formData 是空的。 - imans77
1
@GregorDoroschenko,是的,我也这样做了(还尝试了enctype),但奇怪的是它又不起作用了。 - imans77
4
$event.target.files有什么用途? - Samarth Saxena
3
如何在你的示例中设置标头?如何定义yourHeadersConfig - Sithys
显示剩余24条评论

43

我在项目中实现了将文件上传到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>

使用 API 所需的 TS 文件

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

1
你有什么方法可以不发送头信息? - Shalom Dahan

20

使用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 });

这是使用方法的最简单示例。若要了解全部功能,请参阅演示.


5
上传图片后如何获取响应?响应会是什么,文档中缺少这部分内容。 - Muhammad Shahzad
3
警告:ng2-file-upload不使用angular的http服务,因此通话不会被MSAL拦截器捕获,因此访问令牌不会自动添加到授权头中。 - ChiefTwoPencils

13
  1. HTML

    <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>

  1. ts文件
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(( ) => {                 
                });     
    }
  1. 后端Spring(Java文件)

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并将上传的文件保存在创建的文件夹中


我们如何检索那个文件?你有什么指导吗? - Siddharth Choudhary
我的Spring服务器运行在8080端口,Angular的运行在3000端口。现在当我将server_url标记为localhost:8080/api/uploadForm时,它会提示CORS不允许! - Siddharth Choudhary
byte[] bytes = file.getBytes(); 这将给出字节流,您可以将其转换为文件。对于CORS问题,您可以在Google中找到解决方案。 - Shafeeq Mohammed
有没有可能在用户在未选择任何文件的情况下直接点击“确定”按钮时返回警告,表示没有选择任何文件? - Catalina
@Siddharth 将以下内容添加到您的Spring控制器注释中:@CrossOrigin(origins = "http://localhost:8080") - Hrvoje T

10

首先,您需要在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();  
}

接下来,我们需要创建图像上传UI的HTML模板。打开src/app/home/home.component.html文件并添加以下内容:

<div [ngStyle]="{'text-align':center; 'margin-top': 100px;}">
   <button mat-button color="primary" (click)="fileUpload.click()">choose file</button>  
   <button mat-button color="warn" (click)="onClick()">Upload</button>  
   <input [hidden]="true" type="file" #fileUpload id="fileUpload" name="fileUpload" multiple="multiple" accept="image/*" />
</div>

查看这个教程以及这篇文章


9

好的,由于这个帖子出现在谷歌的前几个搜索结果中,针对其他有同样问题的用户,你无需重新发明轮子。如trueboroda所指出的那样,ng2-file-upload库可以简化使用Angular 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上传文件


1
谢谢提供链接。在桌面上上传工作正常,但是我无论如何都无法让iOS等移动设备上传工作正常。我可以从相机胶卷中选择文件,但上传总是失败。有什么想法吗?顺便说一下,这是在移动Safari中运行,而不是安装的应用程序中。 - ScottN
1
嗨 @ScottN,欢迎您。也许问题来自您正在使用的浏览器?您尝试用另一个浏览器测试一下吗? - Mohamed Makkaoui
1
嗨@Mohamed Makkaoui,感谢您的回复。我在iOS上尝试了Chrome,结果仍然相同。我很好奇这是否是向服务器发布时的标题问题?我正在使用一个自定义的.Net编写的WebAPI,而不是AWS FYI。 - ScottN
1
嗨@ScottN,除非您使用此链接https://developers.google.com/web/tools/chrome-devtools/remote-debugging/调试代码并查看您收到的错误消息,否则我们将无法确定是否存在标题问题。 - Mohamed Makkaoui
另一方面,您不需要包来实现简单的文件上传。API都在那里,您无需重新发明任何东西。 - Kim

8

我正在使用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


7

个人而言,我使用ngx-material-file-input作为前端,Firebase作为后端。更具体地说,是将Firebase的云存储与Cloud Firestore相结合作为后端。以下是一个示例,它限制文件大小不超过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();
    }
  }

storage.rules

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

2
看起来很不错,但是为什么在 contactForm 声明中需要 toString() 方法呢? - trungk18
1
@trungk18 再次检查一下,你是对的 toString() 是无用的,我已经编辑了我的答案。对于那些阅读此评论的人,在 contact.component.tsfileUploader 结尾处,我有 ])].toString()})。现在它变成了简单的:])]}) - Daniel Danielecki

6

使用Angular和Node.js(Express)完成文件上传的完整示例

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

Node.js 代码

文件上传 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
}
}

1
httpService 是从哪里来的? - James
@James,httpService是Angular的http模块,用于向服务器发起http调用。您可以使用任何http服务。导入语句如下:{ HttpClientModule } from '@angular/common/http'; - Rohit Parte

5
这是我上传 Excel 文件的方法:
目录结构:
app
|-----uploadcomponent
           |-----uploadcomponent.module.ts
           |-----uploadcomponent.html
|-----app.module.ts
|-----app.component.ts
|-----app.service.ts

uploadcomponent.html

<div>
   <form [formGroup]="form" (ngSubmit)="onSubmit()">
     <input type="file" name="profile"  enctype="multipart/form-data" accept=".xlsm,application/msexcel" (change)="onChange($event)" />
     <button type="submit">Upload Template</button>
     <button id="delete_button" class="delete_button" type="reset"><i class="fa fa-trash"></i></button> 
   </form>           
</div>

uploadcomponent.ts

    import { FormBuilder, FormGroup, ReactiveFormsModule } from '@angular/forms';
    import { Component, OnInit } from '@angular/core';
    ....
    export class UploadComponent implements OnInit {
        form: FormGroup;
        constructor(private formBuilder: FormBuilder, private uploadService: AppService) {}
        ngOnInit() {  
            this.form = this.formBuilder.group({
               profile: ['']
            });
        }

        onChange(event) {
            if (event.target.files.length > 0) {
              const file = event.target.files[0];

              this.form.get('profile').setValue(file);
              console.log(this.form.get('profile').value)
            }
        }

        onSubmit() {
           const formData = new FormData();
           formData.append('file', this.form.get('profile').value);

           this.uploadService.upload(formData).subscribe(
             (res) => {
               this.response = res;

               console.log(res);

             },
             (err) => {  
               console.log(err);
             });
         }
    }

app.service.ts

    upload(formData) {
        const endpoint = this.service_url+'upload/';
        const httpOptions = headers: new HttpHeaders({    <<<< Changes are here
            'Authorization': 'token xxxxxxx'})
        };
        return this.http.post(endpoint, formData, httpOptions);
    }

我在后端使用Django REST框架。
models.py

from __future__ import unicode_literals
from django.db import models
from django.db import connection
from django_mysql.models import JSONField, Model
import uuid
import os


def change_filename(instance, filename):
    extension = filename.split('.')[-1]
    file_name = os.path.splitext(filename)[0]
    uuid_name = uuid.uuid4()
    return file_name+"_"+str(uuid_name)+"."+extension

class UploadTemplate (Model):
    id = models.AutoField(primary_key=True)
    file = models.FileField(blank=False, null=False, upload_to=change_filename)

    def __str__(self):
        return str(self.file.name)

views.py.

class UploadView(APIView):
    serializer_class = UploadSerializer
    parser_classes = [MultiPartParser]       

    def get_queryset(self):
        queryset = UploadTemplate.objects.all()
        return queryset

    def post(self, request, *args, **kwargs):
        file_serializer = UploadSerializer(data=request.data)
        status = None
        message = None
        if file_serializer.is_valid():
            file_serializer.save()
            status = "Success"
            message = "Success"
        else:
            status = "Failure"
            message = "Failure!"
        content = {'status': status, 'message': message}
        return Response(content)

序列化器.py。

from uploadtemplate.models import UploadTemplate
from rest_framework import serializers

class UploadSerializer(serializers.ModelSerializer):
    class Meta:
        model = UploadTemplate
        fields = '__all__'   

urls.py.

router.register(r'uploadtemplate', uploadtemplateviews.UploadTemplateView, 
    base_name='UploadTemplate')
urlpatterns = [
    ....
    url(r'upload/', uploadtemplateviews.UploadTemplateView.as_view()),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

MEDIA_URL和MEDIA_ROOT被定义在项目的settings.py中。

谢谢!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接