使用Angular 2和Spring上传文件
问题描述:
使用Angular客户端和Spring服务器上传文件有没有简单的方法?在找到最简单的工作解决方案之前,我必须搜索不同的问题/答案,而不使用外部库。 下面的解决方案,我发现在StackOverflow上找到几个答案,使用StackOverflow问题/答案样式,希望它有帮助。使用Angular 2和Spring上传文件
答
我找到的解决方案。只要我再次找到我从中取得代码的答案,我会提及它们。
文件upload.component.html
<input type="file"
(change)="fileChange($event)"
placeholder="Upload file"
accept=".pdf,.doc,.docx">
文件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)
)
}
}
}
春控制器:
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+ PR很好的支持上传文件。
这里是我的解决方案:
它离开的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)
);
}
}
}