前端
<div>
<label for="file">选择文件</label>
<input type="file" id="file" (change)="uploadImg($event.target.files)" multiple="multiple" accept="image/*">
</div>
ts文件 先引入http
import {Http, URLSearchParams, RequestOptions} from '@angular/http'; // 发送请求有关的类
然后把http添加到 constructor中
constructor(
@Inject(MD_DIALOG_DATA) public data: any,
private http: Http,) {
}
请求方法
uploadImg(files) {
var serverurl = "http://localhost:9090/api/v1.0/bs/WaterStation/waterStationImg";
let param = new FormData();
let file = files[0];
param.append("file", file);
param.append('resKind', '2');
param.append('resType', '1');
return this.http.post(serverurl, param, null).toPromise()
.then(response => {
let data = response.json();
if (data.resp.code == 1000) {
swal('系统提示', data.resp.msg, 'error')
} else if (data.resp.code == 200) {
swal('系统提示', data.resp.msg, 'success')
}
})
}
后台接收
@PostMapping("/waterStationImg")
public ServerResp<TextResourceResp> waterStationImg(@RequestParam(value = "file",required = false) MultipartFile file ,@RequestParam(value = "resKind") String resKind,@RequestParam(value = "resType") String resType) {
TextResourceResp resp = new TextResourceResp();
try {
resp = textResourceService.uploadImg(file, resKind, resType);
}catch (Exception e){
e.printStackTrace();
}
return ServerResp.createBySuccess(resp,0);
}
@Override
public TextResourceResp uploadImg(MultipartFile file, String resKind, String resType) {
TextResourceResp resp = new TextResourceResp();
if (file ==null){
resp.setMsg("请选择要上传的图片");
resp.setCode(1000);
}
//获取文件后缀
String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1, file.getOriginalFilename().length());
if (!"jpg,jpeg,gif,png".toUpperCase().contains(suffix.toUpperCase())) {
resp.setCode(1000);
resp.setMsg("请选择jpg,jpeg,gif,png格式的图片");
}
long size = file.getSize();
SimpleDateFormat formatter1 = new SimpleDateFormat("yyyyMMdd");
String formatStr1 = formatter1.format(new Date());
String savePath = localAddressPhoto + formatStr1;
File file1 = new File(savePath);
if (!file1.exists()) {
file1.mkdirs();
}
//通过UUID生成唯一文件名
String filename = UUID.randomUUID().toString().replaceAll("-", "") + "." + suffix;
try {
//将文件保存到指定目录
file.transferTo(new File(savePath+"/"+filename));
} catch (Exception e) {
e.printStackTrace();
resp.setCode(1000);
resp.setMsg("保存图片异常");
return resp;
}
String url = networkAddressPhoto + formatStr1 + "/" + filename;
TextResource vo = new TextResource();
vo.setResName(filename);
vo.setResLocalPath(savePath);
vo.setResUrl(url);
vo.setResSize((int) size);
vo.setResType(Integer.parseInt(resType));
vo.setResKind(Integer.valueOf(resKind));
vo.setStatus(1);
vo.setCreateDate(new Date());
textResourceMapper.insertSelective(vo);
resp.setId(vo.getId());
resp.setResType(Integer.parseInt(resType));
resp.setResUrl(url);
resp.setCode(200);
resp.setMsg("保存图片成功");
return resp;
}
|