Is there a simple way to upload a file using an Angular client and a Spring server? I had to search through different questions/answers before finding the simplest working solution, using Angular without external libraries. Below the solution I found putting together several answers that I found on StackOverflow, using the StackOverflow question/answer style, hoping it helps.
Asked
Active
Viewed 4,873 times
2 Answers
1
The solution I found. As soon as I find again the answers from which I took the code, I will put a reference to them.
file-upload.component.html
<input type="file"
(change)="fileChange($event)"
placeholder="Upload file"
accept=".pdf,.doc,.docx">
file-upload.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)
)
}
}
}
Spring controller:
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();
}
}
}

Luigi Rubino
- 564
- 1
- 7
- 17
0
Angular 2+ provides good support for uploading file.
Here is my solution :
It is very important to leave the Content-Type empty. If you set the 'Content-Type' to 'multipart/form-data' the upload will not work !
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)
);
}
}
}

abahet
- 10,355
- 4
- 32
- 23