是否有使用Angular客户端和Spring服务器上传文件的简单方法?在找到最简单的工作解决方案之前,我必须搜索不同的问题/答案,使用Angular而不使用外部库。 在解决方案下面,我发现我在StackOverflow上找到了几个答案,使用StackOverflow问题/答案样式,希望它有所帮助。
答案 0 :(得分:1)
我发现的解决方案。一旦我再次找到了我从中获取代码的答案,我就会引用它们。
文件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)
)
}
}
}
Spring控制器:
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();
}
}
}
答案 1 :(得分:0)
Angular 2+为上传文件提供了很好的支持。
这是我的解决方案:
将 Content-Type 留空是非常重要。如果您设置了“内容类型”&#39;到&#39; multipart / form-data&#39;上传无效!
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)
);
}
}
}