<form (ngSubmit)="doSubmit()" enctype="multipart/form-data">
<mat-label>文件</mat-label>
<input name="file" type="file" (change)="upload($event)">
<input type="submit" aria-label="SAVE" value="确定上传" style="color: blue;">
</form>
ts部分:
file: any;
upload(e: any): void {
this.file = e.target.files[0];
if (this.file != null) {
this.msg.success('已经选择文件');
}
console.log(this.file);
// const formData: FormData = new FormData();
// formData.append('file', this.file);
// this.http.post(environment.frontPath + '/sys/test/outImport', formData).subscribe(res => {
// if (res.statusCode == 200) {
// this.msg.success('上传成功');
// }
// })
}
doSubmit(): void {
console.log(111);
const formData: FormData = new FormData();
formData.append('file', this.file);
this.http.post(environment.frontPath + '/sys/test/outImport', formData).subscribe(res => {
if (res.statusCode == 200) {
this.msg.success('上传成功');
}
})
}
后台java接收文件处理
@RequestMapping(value = "/outImport")
@ResponseBody
public Object outImport(@RequestParam(value = "file") MultipartFile file) {
try {
if (file.isEmpty()) {
System.out.println("文件为空空");
return NetResponse.ok("文件为空");
}
String fileName = file.getOriginalFilename(); // 文件名
System.out.println(fileName);
System.out.println(222188888);
String suffixName = fileName.substring(fileName.lastIndexOf(".")); // 后缀名
System.out.println(suffixName);
String filePath = "E://temp-rainy//"; // 上传后的路径
fileName = UUID.randomUUID() + suffixName; // 新文件名
File dest = new File(filePath + fileName);
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
try {
file.transferTo(dest);
} catch (IOException e) {
e.printStackTrace();
}
return NetResponse.ok("操作成功");
} catch (Exception e) {
return NetResponse.error(NetResponse.ERROR,"操作失败", e);
}
}