使用角度4将zip文件上传到弹簧控制器

问题描述 投票:3回答:2

我想从角4上传.zip文件到服务器(弹簧控制器)。请建议怎么做?

提前致谢

angular multipartform-data spring-rest
2个回答
2
投票

1)看看这里: https//angular.io/guide/http#making-a-post-request

因此,您可以构建一个服务,当您在表单中按提交时会触发该服务,该表单会附加文件,无论是zip,img还是其他任何内容都可以用于POST请求。

2)在您的模板中,您可以使用类似的东西:

<form>
  <input type="file" accept=".zip,application/octet-stream,application/zip,application/x-zip,application/x-zip-compressed">
  <input type="submit">
</form>

3)看看这里强制文件扩展名: https//www.hongkiat.com/blog/css3-attribute-selector/


2
投票

经过一些学习,我找到了如何将文件(.zip / .txt /任何其他文件格式)从角度(4/5)上传到弹簧/静止控制器的答案。 在下面写下我的学习内容,为那些看起来相同的人。:)

前端编码::

1. HTML(例如UploadFile.component.html):

<input type="file" formControlName="uploadFile" (change)="uploadFileToServer($event)"/>

2.组件(例如UploadFile.component.ts):

import { Component } from '@angular/core';
import { RequestOptions, Headers, Http } from '@angular/http';
@Component({
  selector: 'file-uploader',
  templateUrl: './uploadFile.component.html',
  styleUrls: ['./uploadFile.component.css'],
})
export class FileUploadComponent {

public uploadFileToServer(event) {
  let fileList: FileList = event.target.files;
  if (fileList.length > 0) {
    let file: File = fileList[0];
    let formData: FormData = new FormData();
    formData.append('uploadFile', file, file.name);
    formData.append('fileType', 'zip');
    let headers = new Headers();
    headers.append('Accept', 'application/json');
    let options = new RequestOptions({ headers: headers });
    this.http.post('domain/urservice', formData, options)
      .map(res => res.json())
      .catch(error => Observable.throw(error))
      .subscribe(
      data => console.log('success'),
      error => console.log(error)
      )
  }
} 

}

(注意 - 此服务器通信调用应存在于某些服务中,而不是在组件中,但为了简单起见,我将其写入组件中)

服务器端编码::

1。 Spring / Rest控制器(FileUploadController.java):

    @RequestMapping(value = "/urservice", method = RequestMethod.POST)
    public void uploadFile(MultipartHttpServletRequest request) throws IOException {

    Iterator<String> itr = request.getFileNames();

    // directory to save file
    String tempDir = System.getProperty("jboss.server.temp.dir");

      MultipartFile file = request.getFile(itr.next());
      String fileType = request.getParameter("fileType");
      String fileName = file.getOriginalFilename();

      File dir = new File(tempDir);
      File fileToImport = null;
      if (dir.isDirectory()) {

        try {
            fileToImport = new File(dir + File.separator + fileName);
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(fileToImport));
            stream.write(file.getBytes());
            stream.close();
        } catch (Exception e) {
            logger.error("Got error in uploading file.");
        }

}
© www.soinside.com 2019 - 2024. All rights reserved.