springboot上传文件

1.FileServiceImpl.java

/**
	 * 文件系统文件路径
	 */
	@Value("${fileSystemPath}")
	private String fileSystemPath;
	/**
	 * 文件系统图片路径
	 */
	@Value("${imgSystemPath}")
	private String imgSystemPath;
/**
	 * 上传文件或图片
	 * 
	 * @param file
	 * @param request
	 * @return
	 */
	@Override
	public ReturnVo uploadFile(MultipartFile file, String type, HttpServletRequest request) {
		String filePath = "";
		// 上传文件写入路径
		String writePath = getLocalDate();
		String fileName = "";
		String videoLength = "";
		// 如果文件不为空
		if (!file.isEmpty()) {
			if (type.equals("img")) {
				writePath = imgSystemPath + writePath;
			} else if (type.equals("file")) {
				writePath = fileSystemPath + writePath;
			} else if (type.equals("video")) {
				writePath = videoSystemPath + writePath;
			}
			fileName = UUID.randomUUID().toString().replaceAll("-", "")
					+ file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
			File dest = new File(new File(writePath).getAbsolutePath() + "/" + fileName);
			// 文件写入路径
			filePath = writePath + "/" + fileName;
			if (!dest.getParentFile().exists()) {
				dest.getParentFile().mkdirs();
			}
			try {
				file.transferTo(dest);
				if (type.equals("video")) {
					videoLength = getVideoDuration(dest, fileName) + "";
				}
			} catch (IOException e) {
				e.printStackTrace();
				return ReturnVo.error("保存失败");
			}
		} else {
			return ReturnVo.error("请上传文件");
		}
		ReturnVo result = new ReturnVo();
		if (type.equals("video")) {
			result.put("videoLength", videoLength + "分钟");
		}
		return result.put("filePath", filePath);
	}

/**
	 * 
	 * @Title: getVideoDuration
	 * @Description: 获取音频播放时长(单位分钟)
	 * @param file
	 * @return

	 */
       public long getVideoDuration(File source, String fileName) {
		long duration = 0;
		try {
			Encoder encoder = new Encoder();
			MultimediaInfo info = encoder.getInfo(source);
			duration = info.getDuration();
			if (source.exists()) {
				source.delete();
			}
			return duration / 1000 / 60;
		} catch (Exception e) {
			e.printStackTrace();
			return duration;
		}
	}

2.FileController.java

/**
	 * 上传图片(图片格式为jpg/jpeg/png)
	 * 
	 * @param file
	 * @param type  文件类型  file img  video
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
	public ReturnVo saveImg(@RequestParam(value = "file") MultipartFile file,
			@RequestParam String type ,             
			HttpServletRequest request) {
		return fileService.uploadFile(file,type,request);
	}

原文地址:https://www.cnblogs.com/xian-yu/p/13262318.html