5

I want to upload .zip file to server (spring rest controller) from angular 4. Please suggest how to do so?

thanks in advance

2 Answers 2

3

After some learning, i have found the answer to how to upload file(.zip/.txt/ any other file format) from angular (4/5) to spring/rest controller. Writing down my learning below for those who looking same thing.:)

Front-end coding ::

1. HTML (eg. UploadFile.component.html):

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

2. Component (eg. 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)
      )
  }
} 

}

(note - this server communication call should be present in some service not in component but for simplicity i am writing it in component)

server-side coding ::

1 . Spring/Rest controller (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.");
        }

}
Sign up to request clarification or add additional context in comments.

Comments

2

1) Have a look here: https://angular.io/guide/http#making-a-post-request

So you can build a service which gets triggered when you press submit in a form, which attaches the file, whatever that is, a zip, img or whatever to the POST request.

2) In your template you can use something similar:

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

3) Have a look here to force the file extention: https://www.hongkiat.com/blog/css3-attribute-selector/

1 Comment

Thanks , so helpful answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.