报错

文件上传接口解析文件时候报错报错信息如下

s.w.m.s.StandardServletMultipartResolver : Failed to perform cleanup of multipart items
java.io.UncheckedIOException: Cannot delete C:UsersusernameAppDataLocalTemptomcat.8080.xxxxworkTomcatlocalhostROOTupload_xxxx_00000000.tmp

使用场景描述

从文件上传接口上传表格文件,然后表格内容进行解析,将解析出的数据存入数据库
需要接口参数 MultipartFile 中,获取InputStream ,以供之后 解析数据逻辑 使用

文件上传接口业务逻辑能够正常执行。但是,控制台会报出如上的错误

报错原因

使用InputStream 之后,没有关闭。导致 tomcat 临时文件无法删除

解决办法就是使用InputStream后,关闭它。

解决方案

1. @Cleanup推荐

使用 Lombok@Cleanup 注解,释放资源

@Cleanup
InputStream inputStream;

代码示例

	@PostMapping("upload")
	@ApiOperation(value = "上传表格文件,解析表格", notes = "")
	public String upload(MultipartFile file) {
		// 表格文件校验逻辑

		// 解析表格,需要从 MultipartFart 获取输入流 InputStream。
		try {
			// 输入流需要关闭,使用 @Cleanup 注解,否则会报异常
			@Cleanup
			InputStream inputStream = file.getInputStream();

			// 表格解析业务逻辑

		} catch (IOException e) {
			e.printStackTrace();
			System.out.println("IOException:" + e);
		}

		return "文件上传成功";
	}

2. IOUtils.closeQuietly

使用 IOUtils.closeQuietly 方法,释放资源。此方法需要finally 代码块中使用。

IOUtils.closeQuietly(inputStream);

示例代码:

import org.apache.tomcat.util.http.fileupload.IOUtils;
	@PostMapping("upload")
	@ApiOperation(value = "上传表格文件,解析表格", notes = "")
	public String upload(MultipartFile file) {
		// 表格文件校验逻辑

		// 解析表格,需要从 MultipartFart 获取到输入流 InputStream。
		InputStream inputStream = null;
		try {
			inputStream = file.getInputStream();

			// 表格解析业务逻辑

		} catch (IOException e) {
			e.printStackTrace();
			System.out.println("IOException:" + e);
		} finally {
			IOUtils.closeQuietly(inputStream);
		}

		return "文件上传成功";
	}

3. InputStream.close()

方法为 Java InputStream 提供的默认方法。

直接关闭输出流。close() 方法,需要finally调用

	if (inputStream != null) {
		try {
			inputStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

代码示例:

	@PostMapping("upload")
	@ApiOperation(value = "上传表格文件,解析表格", notes = "")
	public String upload(MultipartFile file) {
		// 表格文件校验逻辑

		// 解析表格,需要从 MultipartFart 获取到输入流 InputStream。
		InputStream inputStream = null;
		try {
			inputStream = file.getInputStream();

			// 表格解析业务逻辑

		} catch (IOException e) {
			e.printStackTrace();
			System.out.println("IOException:" + e);
		} finally {
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		return "文件上传成功";
	}

原文地址:https://blog.csdn.net/sgx1825192/article/details/131148006

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任

如若转载,请注明出处:http://www.7code.cn/show_39908.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱suwngjj01@126.com进行投诉反馈,一经查实,立即删除

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注