一:简介

  1. 最近项目中有用到将图片及文件上传到服务器上,并实现从服务器获取文件以及删除服务器文件信息

二:编码

  1. 上传文件
/**
     * @Author: guwenhai
     * @Description:    图片上传
     * @param file 文件信息
     * @param absoluteImgPath 绝对路径地址
     * @Date: 2021-03-27 16:42
     */
public static List<Map<String,Object>> imgUpload(MultipartFile[] file,String absoluteImgPath){
    List<Map<String,Object>> list = new ArrayList<>();
    for (int i = 0; i < file.length; i++) {
        if(!file[i].isEmpty()){
            String originalFilename = file[i].getOriginalFilename();
            //随机生成文件名
            String fileName = RandomUtils.random() + originalFilename;
            File dest = new File(absoluteImgPath + fileName);
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            String feedPicture = fileName;
            try {
                file[i].transferTo(dest);
                Map<String,Object> map = new HashMap<>();
                map.put("name",originalFilename);
                map.put("url",feedPicture);
                list.add(map);
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }
    }
    return list;
}
  1. 获取文件
public void showImg(HttpServletResponse response) {
    //查询当前登录用户图片地址
    String pathName = "";
    File imgFile = new File(pathName);
    FileInputStream fin = null;
    OutputStream output = null;
    try {
        output = response.getOutputStream();
        fin = new FileInputStream(imgFile);
        byte[] arr = new byte[1024 * 10];
        int n;
        while ((n = fin.read(arr)) != -1) {
            output.write(arr, 0, n);
        }
        output.flush();
        output.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
  1. 删除文件
public void removeFile() {
   String imgAddress  = "";	//路径地址
   File file = new File(imgAddress);
   if (file.exists() == true){
       file.delete();
   }
}