spring 文件上传功能

上传到本地

1、配置文件

properties

#文件上传
# 开启上传功能
spring.servlet.multipart.enabled=true
#文件写入磁盘的阈值,默认是0
spring.servlet.multipart.file-size-threshold=2KB
#单个文件的最大值2MB
spring.servlet.multipart.max-file-size=20MB
#多个文件上传时的总大小 值,默认是10MB
spring.servlet.multipart.max-request-size=100MB
#是否延迟解析,默认是false
spring.servlet.multipart.resolve-lazily=false
#文件存放路径
file.upload-dir=src/main/resources/statistic/uploads

yaml格式

application:
  #版本
  version: 1.0.0
  #文件上传路径
  profile: D:/profile/
spring:
  servlet:
    multipart:
      max-file-size: 30MB
      max-request-size: 30MB

2、定义一个文件返回对象

@Data
public class UploadFileResponse implements IValueObject {

	private static final long serialVersionUID = 2765979176186804822L;

	private String fileName;

	private String fileDownloadUri;

	private String fileType;

	private long fileSize;

}

3、controller层

public interface IFileOperateController {

	List<UploadFileResponse> uploadFiles(MultipartFile[] mutipartFiles, HttpServletRequest request);

	String downLoadFile(String fileName, HttpServletResponse response);

	List<UploadFileResponse> getResponseFiles();
}

4、service层

@Service
@Transactional(propagation = Propagation.REQUIRED)
public class FileUploadService implements IFileUploadService {

	/**
	 * 项目根路径下的目录
	 */
	private static String UPLOAD_PATH_PREFIX = "file.upload-dir";

	/**
	 * 上传并存储文件.
	 */
	@Override
	public List<UploadFileResponse> loadAndStoreFiles(final MultipartFile[] mutipartFiles,
			final HttpServletRequest request) {
		final List<UploadFileResponse> fileLists = new ArrayList<>();
		if (ObjectUtils.isEmpty(mutipartFiles)) {
			return fileLists;
		}
		// 文件上传的真实路径
		final File fileRealPath = getRealPath();
		if (null == fileRealPath) {
			throw new FileException(EntireExResConst.EX_CHECK_FAILED, "文件上传失败!");
		}

		// 判断文件夹是否存在
		if (!fileRealPath.exists()) {
			// 递归生成文件夹
			fileRealPath.mkdirs();
		}
		final int size = mutipartFiles.length;
		for (int i = 0; i < size; i++) {
			// 上传文件名称.
			String oldName = mutipartFiles[i].getOriginalFilename();
			// 存放的文件的名称.
			// String newName = UUID.randomUUID().toString()
			// + oldName.substring(oldName.lastIndexOf("."), oldName.length());
			// 构建真实的文件路径
			final File resultFile = new File(fileRealPath + File.separator + oldName);
			// 转存文件到指定路径,如果文件名重复的话,将会覆盖掉之前的文件,这里是把文件上传到 “绝对路径”
			try {
				mutipartFiles[i].transferTo(resultFile);
				UploadFileResponse uploadFileResponse = new UploadFileResponse(oldName, fileRealPath.getAbsolutePath(),
						"", Long.valueOf(mutipartFiles[i].getSize()));
				fileLists.add(uploadFileResponse);
			} catch (Exception e) {
				LOG.error("\n>>>>>>文件上传失败,文件名为: " + oldName);
				throw new FileException(EntireExResConst.EX_CHECK_FAILED, "文件上传失败!");
			}
		}
		return fileLists;
	}

	/**
	 * 从不同的系统中获取真实路径.
	 */
	private File getRealPath() {
		String os = System.getProperty("os.name");
		// 项目根路径下文件夹
		String uploadUrl = PropertyConfigUtil.getProperty(UPLOAD_PATH_PREFIX);
		final File fileRealPath;
		if (os.toLowerCase().startsWith("win")) {// windows系统
			// 项目根目录的绝对路径 + 指定文件夹路径
			String path = System.getProperty("user.dir") + File.separator + uploadUrl;
			fileRealPath = new File(path);
			LOG.info("\n>>>>>(win)文件上传保存的路径为:" + fileRealPath);
			
		} else {
			// linux系统
			File rootPath = null;
			try {
				rootPath = new File(ResourceUtils.getURL("classpath:").getPath());
			} catch (Exception e) {
				LOG.error("\n>>>>>>文件路径未找到! ");
				return null;
			}
			if (!rootPath.exists()) {
				rootPath = new File("");
			}
			fileRealPath = new File(rootPath.getAbsolutePath() + File.separator + uploadUrl);
			LOG.info("\n>>>>>(linux)文件上传保存的路径为:" + fileRealPath);
		}
		return fileRealPath;
	}

	/**
	 * 文件下载.
	 */
	@Override
	public String downLoadFile(String fileName, final HttpServletResponse response) {
		// 获取到服务器文件存储真实路径
		final File realPath = getRealPath();
		final List<File> files = getAllFiles(realPath);
		if (CollectionUtils.isEmpty(files)) {
			return "success";
		}
		files.forEach(file -> {
			if (fileName.equals(file.getName())) {
				response.setCharacterEncoding("UTF-8");
				response.setContentType("application/force-download");// 设置强制下载不打开
				response.addHeader("Content-Disposition", "attachment;fileName=" + file);// 设置文件名
				fileDownLoad(file, response);
			}
		});
		return "success";
	}

	/**
     * 文件下载
	 */
	private boolean fileDownLoad(final File file, HttpServletResponse response) {
		byte[] buffer = new byte[1024];
		FileInputStream fis = null;
		BufferedInputStream bis = null;
		try {
			fis = new FileInputStream(file);
			bis = new BufferedInputStream(fis);
			OutputStream os = response.getOutputStream();
			int i = bis.read(buffer);
			while (i != -1) {
				os.write(buffer, 0, i);
				i = bis.read(buffer);
			}
			return true;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (bis != null) {
				try {
					bis.close();
				} catch (IOException e) {
					LOG.err();
				}
			}
			if (fis != null) {
				try {
					fis.close();
				} catch (IOException e) {
					LOG.err();
				}
			}
		}
		return false;
	}

	/**
	 * 获取所有上传文件信息.
	 */
	@Override
	public List<UploadFileResponse> getResponseFiles() {
		final List<UploadFileResponse> uploadFileResponses = new ArrayList<>();
		final File realPath = getRealPath();
		final List<File> files = getAllFiles(realPath);
		if (!CollectionUtils.isEmpty(files)) {
			files.forEach(file -> {
				uploadFileResponses
						.add(new UploadFileResponse(file.getName(), realPath.getAbsolutePath(), "", file.length()));
			});
		}
		return uploadFileResponses;
	}

	/**
	 * 获取该路径下的所有文件.
	 */
	private List<File> getAllFiles(final File realPath) {
		final List<File> list = new ArrayList<>();
		File baseFile = new File(realPath.getAbsolutePath());
		if (baseFile.isFile() || !baseFile.exists()) {
			return list;
		}
		File[] files = baseFile.listFiles();
		if (files.length != 0) {
			for (File file : files) {
				if (file.isDirectory()) {
					continue;
				} else {
					list.add(file);
				}
			}
		}
		return list;
	}
}

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值