【问题标题】:file upload with Angular 2 and Spring使用 Angular 2 和 Spring 上传文件
【发布时间】:2017-11-02 05:46:39
【问题描述】:

有没有一种使用 Angular 客户端和 Spring 服务器上传文件的简单方法?在找到最简单的工作解决方案之前,我必须搜索不同的问题/答案,使用没有外部库的 Angular。 在解决方案下方,我发现将我在 StackOverflow 上找到的几个答案放在一起,使用 StackOverflow 问题/答案样式,希望对您有所帮助。

【问题讨论】:

    标签: spring angular file-upload


    【解决方案1】:

    我找到的解决方案。一旦我再次找到我从中获取代码的答案,我将引用它们。

    File Upload In Angular 2?

    文件上传.component.html

        <input type="file" 
               (change)="fileChange($event)"
               placeholder="Upload file" 
               accept=".pdf,.doc,.docx">
    

    文件上传.component.ts

        import { Component } from '@angular/core';
        import { RequestOptions, Headers, Http } from '@angular/http';
        import { Observable } from 'rxjs';
    
        @Component({
          selector: 'file-upload',
          templateUrl: './file-upload.component.html'
        })
        export class FileUploadComponent {
    
          apiEndPoint = "http://localhost:8080/mySpringApp/upload";
    
          constructor(private http: Http) {
          }
    
          fileChange(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);
              let headers = new Headers();
              headers.append('Accept', 'application/json');
              let options = new RequestOptions({ headers: headers });
              this.http.post(`${this.apiEndPoint}`, formData, options)
                .map(res => res.json())
                .catch(error => Observable.throw(error))
                .subscribe(
                data => console.log('success'),
                error => console.log(error)
                )
            }
          }
        }
    

    弹簧控制器:

        package unisvid.sessionManager.server.controller;
    
        import java.io.BufferedOutputStream;
        import java.io.File;
        import java.io.FileOutputStream;
        import java.io.IOException;
        import java.util.Iterator;
    
        import org.springframework.web.bind.annotation.CrossOrigin;
        import org.springframework.web.bind.annotation.RequestMapping;
        import org.springframework.web.bind.annotation.RequestMethod;
        import org.springframework.web.bind.annotation.RestController;
        import org.springframework.web.multipart.MultipartFile;
        import org.springframework.web.multipart.MultipartHttpServletRequest;
    
        @CrossOrigin(origins = "*")
        @RestController
        public class FileUploadController {
    
          @RequestMapping(value = "/upload", method = RequestMethod.POST)
          public void UploadFile(MultipartHttpServletRequest request) throws IOException {
    
            Iterator<String> itr = request.getFileNames();
            MultipartFile file = request.getFile(itr.next());
            String fileName = file.getOriginalFilename();
            File dir = new File("/Users/luigi/Documents/tmp/");
            if (dir.isDirectory()) {
              File serverFile = new File(dir, fileName);
              BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
              stream.write(file.getBytes());
              stream.close();
            }
          }
        }
    

    【讨论】:

      【解决方案2】:

      Angular 2+ 为上传文件提供了良好的支持。

      这是我的解决方案:

      Content-Type 留空非常重要。如果您将“Content-Type”设置为“multipart/form-data”,则上传将不起作用!

      upload.component.html

      <input type="file" (change)="fileChange($event)" name="file" />
      

      upload.component.ts

      export class UploadComponent implements OnInit {
          constructor(public http: Http) {}
      
          fileChange(event): void {
              const fileList: FileList = event.target.files;
              if (fileList.length > 0) {
                  const file = fileList[0];
      
                  const formData = new FormData();
                  formData.append('file', file, file.name);
      
                  const headers = new Headers();
                  // It is very important to leave the Content-Type empty
                  // do not use headers.append('Content-Type', 'multipart/form-data');
                  headers.append('Authorization', 'Bearer ' + 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9....');
                  const options = new RequestOptions({headers: headers});
      
                  this.http.post('https://api.mysite.com/uploadfile', formData, options)
                       .map(res => res.json())
                       .catch(error => Observable.throw(error))
                       .subscribe(
                           data => console.log('success'),
                           error => console.log(error)
                       );
              }
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2020-11-28
        • 2018-04-07
        • 2020-04-19
        • 2017-07-26
        • 2018-01-02
        • 2016-06-21
        • 2016-10-14
        • 2021-04-07
        • 1970-01-01
        相关资源
        最近更新 更多