Java 基于springBoot 上传文件

@RequestMapping("/uploadFile")
    @ResponseBody
    public Map<String, Object> uploadFile (@RequestParam(value = "file") MultipartFile[] file, HttpServletRequest requestNew) {
        log.info("批量上传文件开始==============");
        Map<String, Object> result = new HashMap<>();
        
        if (file == null || file.length == 0) {
            result.put("msg", "上传失败,请先选择文件");
            return result;
        }
        long start = System.currentTimeMillis();
        try {
            SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd");
            String dirName = sf.format(new Date());
            String filePath = "你需要存储的服务器路径" + "/" + dirName;//excel生成的文件路径
            File fileNew = new File(filePath);
            if (!fileNew.exists()) {//判断目录是否存在
                fileNew.mkdirs();
            }
            List<String> showUrls = new ArrayList<>();
            for (MultipartFile singleFile : file) {
                log.info("上传单个文件开始;文件名:"+ singleFile.getOriginalFilename());
      
                long localStartTime = System.currentTimeMillis();
                //生成文件名称已uuid命名
                String uuid = UUID.randomUUID().toString().replaceAll("-","");
                String fileNameOld = singleFile.getOriginalFilename();
                String[] fileNameArr = fileNameOld.split("\\.");
                String fileName = uuid + "." + fileNameArr[fileNameArr.length-1];
                String filePathNew = filePath +"/" + fileName;
                File newFile=new File(filePathNew);
                singleFile.transferTo(newFile);
                String basePath = requestNew.getScheme()+"://"+requestNew.getServerName();
                log.info("上传单个文件结束,【" + fileNameOld +"】所耗时间:" + (System.currentTimeMillis() - localStartTime) + "ms");
                String showUrl = basePath  +"/production/" + dirName + "/" + fileName;
                showUrls.add(showUrl);
            }
            result.put("showUrls", showUrls);
            log.info("批量上传文件结束==============总耗时:" + (System.currentTimeMillis() - start ) +" ms");
        } catch (Exception e) {
            log.error("批量上传到服务器出错!", e);
        }
        return result;
    }

请求方式

image

删除文件

import java.io.File;
 
public class TestMain {
	
	public static void main(String[] args) {
		String dir = "D:\\CloudMusic";
		circleMethod(dir);
	}
	
	/**
	 * 
	 * @param dirPath
	 *          文件所在的路径
	 */
	private static void circleMethod(String dirPath) {
		File file = new File(dirPath);
		if (file.isDirectory()) {//if(file.isDirectory);如果path表示的是一个目录则返回true。
			String[] dirPathList = file.list();
			for (int i = 0; i < dirPathList.length; i++) {
				String filePath = dirPath + File.separator + dirPathList[i];
				File fileDelete = new File(filePath);
				if (fileDelete.getName().equals("test1111.txt")) {
					fileDelete.delete();
				}
				//circleMethod(filePath);
			}
		}
	}
}

或者

//删除指定文件
				String dir = "/.../.../.../.../...";//路径
				FileUtil.circleMethod(dir,"test.jpg,aaa.jar,bbb.war");
 
 
 
 
/**
	 * 
	 * @param filePath  文件路径
	 * @param fileNames   文件名称
	 */
	public static void delMethod(String filePath,String fileNames) {
		String[] name = fileNames.split(",");//多个文件,逗号分割
		for (String fileName : name) {
			File file = new File(filePath+"\\"+fileName);
			if(file.exists() && file.isFile()) {
				file.delete();
			}
		}
	}

如果使用异步@ASYNC 则MultipartFile会出现异常,异步情况下物理缓存会被清空,实际存储的时候,会报错找不到文件

异步,情况下可以使用文件流进行处理,但是相当于是吧上传文件重组了,md5值会改变

 for (MultipartFile mf : files) {
                dfSvc.addFile(mf.getInputStream(), mf.getOriginalFilename(), orderType, null, fileSource, filePath, userName, true);
            }
			
			
public R addFile(InputStream ip, String originalFilename, String orderType, String orderCode, String fileSource, String filePath, String userName, boolean isBatchUpload) {
        String filePathNew = "";
        R r = R.ok();
        try {
            log.info("上传单个文件开始;文件名:" + originalFilename);
            long localStartTime = System.currentTimeMillis();
            //生成文件名称已uuid命名
            String uuid = originalFilename + UUID.randomUUID().toString().replaceAll("-", "");
            String[] fileNameArr = originalFilename.split("\\.");
            String fileName = uuid + "." + fileNameArr[fileNameArr.length - 1];
            filePathNew = filePath + "/" + fileName;

            try {
                FileOutputStream fos = new FileOutputStream(filePathNew);
                byte[] b = new byte[1024];
                while ((ip.read(b)) != -1) {
                    fos.write(b);// 写入数据
                }
                ip.close();
                fos.close();// 保存数据
            } catch (Exception e) {
                e.printStackTrace();
            }

            if (res.hasError()) {
                //删除服务器文件
                delMethod(filePathNew);
                r = R.fail("上传失败:" + res.getMsg());
                return r;
            }
            String loga = "上传单个文件结束,【" + originalFilename + "】服务器所耗时间:" + (System.currentTimeMillis() - localStartTime) + "ms;(非网络耗时)";
            log.info(loga);
            r = R.ok(null, loga);
            return r;
        } catch (Exception e) {
            log.error(e.toString());
            //删除服务器文件
            delMethod(filePathNew);
            r = R.fail("上传失败:" + e.toString());
            return r;
        } finally {

        }

    }
posted @ 2022-12-13 17:47  darling331  阅读(157)  评论(0编辑  收藏  举报