上传(此时就应该保存文件到本地了)
@Override
public ResultMap upload(MultipartFile file) throws IOException {
//若上传附件大小大于10M=10485760=10*1024*1024k
// if (multipartFile.getSize() > 10485760) {
// return ResultMap.error("上传图片不能大于10M");
// }
String path = partyFileUrl;
File dir = new File(path);
if (!dir.exists()) {
dir.mkdirs();
}
// 获取文件的后缀
String suffix = "." + file.getOriginalFilename().substring(file.getOriginalFilename().indexOf(".") + 1);
// 生成文件名
String fileName = "/" + System.currentTimeMillis() + RandomStringUtils.random(32, true, true) + suffix;
File saveFile = new File(partyFileUrl + fileName);
file.transferTo(saveFile);
// 此处partyFile为文件夹名,可以在配置文件中写好获取
String resPath = "partyFile" + fileName;
return ResultMap.success("上传成功", resPath);
}
保存文件
@Override
public ResultMap saveFile(TbVideo tbVideo, String path) {
String fileExtension = null;
String fileName = null;
fileExtension = path.substring(path.lastIndexOf(".")); //获取后缀名
//保存记录
if (StringUtils.isBlank(tbVideo.getId())) {
//在配置中 videoAndimgIp=192.168.xx.xx:8x8x/partyFile
tbVideo.setVideoUrl("http://" + videoAndimgIp + "" + path.substring(path.lastIndexOf("/")+1));
tbVideo.setResourcesType(fileExtension);
tbVideo.setCreateTime(new Date());
tbVideoMapper.insert(tbVideo);
} else {
tbVideoMapper.updateById(tbVideo);
}
return ResultMap.init(Const.RRTURN__TABLE_STATUS, Const.SAVE_SUCCESS, "http://" + videoAndimgIp + "" + path.substring(path.lastIndexOf("/")+1));
}
del
@Override
public ResultMap delFile(Map map) {
TbVideo tbVideo = tbVideoMapper.selectById(map.get("id").toString());
boolean deleteImgFile = false;
boolean deleteVideoFile = false;
if (tbVideo.getImgUrl() != null && !tbVideo.getImgUrl().equals("")){
// 获取数据库中的字符串并拼写成本地存储文件的地址,使之删除(index+1是因为 / 与文件系统格式不符合)
String ImgUrl = getJarFilePath() + "/partyFile/" + tbVideo.getImgUrl().substring(tbVideo.getImgUrl().lastIndexOf("/") + 1);
System.out.println(ImgUrl);
File ImgFile = new File(ImgUrl);
// 路径为文件且不为空则进行删除
if (ImgFile != null && ImgFile.exists()) {
deleteImgFile = ImgFile.delete();
}
}
// 文件的删除
if(tbVideo.getVideoUrl() != null && !tbVideo.getVideoUrl().equals("")){
String VideoUrl = getJarFilePath() + "/partyFile/" + tbVideo.getVideoUrl().substring(tbVideo.getVideoUrl().lastIndexOf("/") + 1);
File VideoFile = new File(VideoUrl);
if (VideoFile != null && VideoFile.exists()) {
deleteVideoFile = VideoFile.delete();
}
}
int deletedatabase = tbVideoMapper.deleteById(map.get("id").toString());
return ResultMap.init(Const.RRTURN__TABLE_STATUS,Const.DELETE_SUCCESS,"deleteImgFile:"+deleteImgFile+",deleteVideoFile:"+deleteVideoFile+",deletedatabase:"+deletedatabase);
}
使用 PathVariable ,直接在网页中打开
// http://192.168.xx.xx:8x8x/party/tb-video/readFile/partyFile/wenjian.houzhuiming
@GetMapping("/readFile/partyFile/{url}")
@ApiOperation(value = "读取文件(完成)")
@ApiImplicitParam(name = "url", value = "文件地址")
public void getFile(@PathVariable String url,HttpServletRequest request , HttpServletResponse response) {
String serverUrl = "E:\\";
String imgType = null;
// 拼接到文件所存放的地址
String imgUrl = serverUrl +"partyFile"+"\\"+ url;
File file = new File(imgUrl);
// 后缀名
String suffixName = url.substring(url.lastIndexOf(".")).toLowerCase();
imgType = "image/" + suffixName.replace(".","");
//判断文件是否存在如果不存在就返回默认图标
// if (!(file.exists() && file.canRead())) {
// file = new File(request.getSession().getServletContext().getRealPath("/")
// + "resource/icons/auth/root.png");
// }
FileInputStream inputStream = null;
try {
inputStream = new FileInputStream(file);
byte[] data = new byte[(int) file.length()];
int length = inputStream.read(data);
inputStream.close();
//setContentType("text/plain; charset=utf-8"); 文本
response.setContentType(imgType + ";charset=utf-8");
OutputStream stream = response.getOutputStream();
stream.write(data);
stream.flush();
stream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
后记
保存的地址可以不使用配置,使用获取jar包地址并创建新文件夹这种方式。
//linux和windows下通用
private String getJarFilePath() {
ApplicationHome home = new ApplicationHome(getClass());
File jarFile = home.getSource();
return jarFile.getParentFile().toString();
}
此时的上传接口
@Override
public ResultMap upload(MultipartFile file) throws IOException {
String path = getJarFilePath() + "/partyFile";
File dir = new File(path);
if (!dir.exists()) {
dir.mkdirs();
}
// 获取文件的后缀
String suffix = "." + file.getOriginalFilename().substring(file.getOriginalFilename().indexOf(".") + 1);
// 生成文件名
String fileName = "/" + System.currentTimeMillis() + RandomStringUtils.random(32, true, true) + suffix;
File saveFile = new File(path + fileName);
file.transferTo(saveFile);
String resPath = "/partyFile" + fileName;
return ResultMap.success("上传成功", resPath);
}
保存到本地后就是静态资源,无需再使用上面的接口获取了,可以使用nginx代理映射到存储文件夹下获取,只需要前端将src设定到这里就好了。
location /partyFile {
root /opt/djian;
index index.html index.htm;
}
再加上图片名即可。
至于图片名是否冲突,已经在上传时解决了——重新生成随机数字的名字。
这样就可以略去再用接口获取资源的开销,可以省去极多资源。