angular部分
html部分 `<input type="file" (change)="onFileChanged($event)">
<button (click)="onUpload()">上传</button>`
ts部分
`selectedFile: string;‘
onFileChanged(event) { this.selectedFile = event.target.files[0]; //this.onUpload(); }
onUpload() { // upload code goes here
const uploadData = new FormData();
uploadData.append('uploadfile', this.selectedFile); this.http.post('http://localhost/manage/uploadPic',uploadData).subscribe( (data:any)=>{ // alert(data); console.log(JSON.stringify(data)); },(err:HttpErrorResponse)=>{ console.log(err.message); } )
}`
服务器端部分 `
’ @PostMapping("uploadPic") @ResponseBody public String uploadPic(MultipartFile uploadfile) throws Exception{
String finename=uploadfile.getOriginalFilename();
String suffixname=uploadfile.getOriginalFilename().substring(finename.lastIndexOf("."));
finename=String.valueOf(System.currentTimeMillis())+suffixname;
String filepath="d:/springbootupload/";
File tf=new File(filepath);
if(!tf.exists()){
tf.mkdir();
}
try {
uploadfile.transferTo(new File(filepath+finename));
return finename;
} catch (IOException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
}
return null; }`
applicatin.properties映射本地路径
`spring.resources.static-locations=file:D://springbootupload
spring.mvc.static-path-pattern=/**`
来源:oschina
链接:https://my.oschina.net/u/1183052/blog/3195911