工具类---文件上传下载工具类

pom.xml导入commons-io坐标

<dependency>
	<groupId>commons-io</groupId>
	<artifactId>commons-io</artifactId>
	<version>2.3</version>
</dependency>

在配置文件中配置项目上传文件保存的位置

#项目上传文件保存的位置
fileSaveDirectory=D:/G(other)/temp/

读取配置文件配置的工具类ConfigReaderUtil

public class ConfigReaderUtil {
  
	public ConfigReaderUtil(){}
	private static Properties props = new Properties(); 
	static{
		try {
			//加载配置文件,需要手动指定配置文件
			props.load(new InputStreamReader(Thread.currentThread().getContextClassLoader().getResourceAsStream("application.properties"),"UTF-8"));		
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/*根据key获取value*/
	public static String getValue(String key){
		return props.getProperty(key).trim();
	}
}

上传下载文件工具类

public class FileUtil {

	// 读取配置文件中上传文件保存的位置
	private static String fileSaveUrl = ConfigReaderUtil.getValue("fileSaveDirectory");

	
	//文件下载
	public static void downloadLawFile(HttpServletResponse response, File file) throws IOException {
		OutputStream os = null;
		InputStream in = null;
		try {
			if (file.exists()) { // 文件存在
				os = response.getOutputStream();
				response.reset();
				response.setContentType("application/octet-stream;charset=utf-8");
				// 设置文件名
				response.setHeader("Content-disposition",
						"attachment; filename=" + new String(file.getName().getBytes("gb2312"), "iso-8859-1"));

				in = new FileInputStream(file);
				byte[] b = new byte[1024 * 1024];
				int length;
				while ((length = in.read(b)) != -1) { // 读取内容放到数组里面
					os.write(b, 0, length);
				}
			} else { // 文件不存在
				response.setContentType("text/html; charset=UTF-8");
				PrintWriter out = response.getWriter();
				out.write("文件不存在,请联系管理员!");
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (in != null) {
				in.close();
			}
			if (os != null) {
				os.close();
			}
		}
	}

	//文件上传进行保存
	public static void uploadFile(MultipartFile file) throws Exception {
		if (file != null) {
			String path = fileSaveUrl; // 文件保存路径
			String filename = file.getOriginalFilename(); // 获取原文件全名,包含文件类型
			//String fileType = StringUtils.getFilenameExtension(filename); //获取文件类型 txt doc png jpg...
			File newFile = new File(path + filename);
			IOUtils.copy(file.getInputStream(), new FileOutputStream(newFile));
		}
	}

使用:

      前端页面

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<script src="/manager/js/jquery-3.4.1.min.js"></script>
	</head>
	<body>
		<input type="file" id="fil">
		<button class="upload">上传</button>
	</body>
</html>

<script> 
	$('.upload').click(function(){
		 var file = $("#fil")[0].files[0];
		 var formData = new FormData();  
		 formData.append("file", file);
		 $.ajax({
             type: 'POST',
             url: '/manager/file/upload',
             data: formData,
             async: false,
             contentType: false,    // 告诉jQuery不要去设置Content-Type请求头
             processData: false,     // 告诉jQuery不要去处理发送的数据
             success: function (resu) {
                
             }
         });
	});
</script>
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<script src="/manager/js/jquery-3.4.1.min.js"></script>
	</head>
	<body>
		<button class="upload">download</button>
	</body>
</html>

<script> 
	$('.upload').click(function(){
		window.location.href="http://localhost:8080/manager/file/download";
	});
</script>

        后端接口Controller

        // 文件上传
	@RequestMapping(value = "/file/upload", method = RequestMethod.POST)
	@ResponseBody
	public String fileUpload(@RequestParam MultipartFile file) throws Exception {
		FileUtil.uploadFile(file);
		return "success";
	}

	// 文件下载 
	@RequestMapping("/file/download")
	@ResponseBody
	public void fileDownload(HttpServletResponse response) throws Exception {
		File file = new File("C:/Users/Lonely/Desktop/work/1.txt");
		FileUtil.downloadLawFile(response, file);
	}
发布了62 篇原创文章 · 获赞 25 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_39115469/article/details/104564267
今日推荐