SpingBoot文件处理

本文介绍了一个使用Spring Security的文件控制器,演示了如何在Java应用中实现文件的上传和下载功能。通过@RestController注解定义RESTful API,@RequestMapping指定URL路径,@PostMapping处理POST请求实现文件上传,同时打印文件名、原始文件名和大小,并将文件保存到指定目录。@GetMapping处理GET请求,用于文件下载,通过设置响应头和使用IO流完成文件传输。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Mevan

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

Java

@RestController
@RequestMapping( value = "/file")
public class FileController {
	
	@PostMapping( value="/upload")
	public FileInfo upload(MultipartFile file) throws IllegalStateException, IOException {
		System.out.println(file.getName());
		System.out.println(file.getOriginalFilename());	//文件原始名
		System.out.println(file.getSize());
		
		String folder = "D:\\Program Files\\Java\\eclipse\\javaProject\\spring-security\\spring-security-demo\\src\\main\\resources\\upload";
		File localFile = new File(folder, new Date().getTime() + file.getOriginalFilename());
		file.transferTo(localFile);	//将上传的文件写到本地的文件中
		return new FileInfo(localFile.getAbsolutePath());
	}
	
	@GetMapping( value="/download")
	public void download(@RequestParam(value = "path" , required = true , defaultValue = "1538896688835springboot原理.txt") String path ,HttpServletRequest request
			,HttpServletResponse response ) throws Exception {
		try (
				//JDK 1.7之后,声明在 try() 括号中的流。回自动关闭
				InputStream inputStream = new FileInputStream(new File("D:\\Program Files\\Java\\eclipse\\javaProject\\spring-security\\spring-security-demo\\src\\main\\resources\\upload\\"
				, path));
				OutputStream outputStream = response.getOutputStream();
			){
			response.setContentType("application/x-download");
			response.addHeader("Content-Disposition", "attachmet;filename=fi32.txt");
			IOUtils.copy(inputStream, outputStream);
			outputStream.flush();
		} 
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值