springMVC的文件上传与下载

本文介绍了一个使用Spring MVC实现的文件上传与下载功能。通过示例代码展示了如何配置MultipartResolver来支持文件上传,如何处理上传的文件并保存到服务器,以及如何提供文件下载服务。同时介绍了依赖项commons-fileupload的版本。

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

<form action="testFileUpload" method="post" enctype="multipart/form-data">
		File:<input type="file" name="file">
		Desc:<input type="text" name="desc">
		<input type="submit" value="submit">
	</form>
	
	<a href="downloadFile?fileName=上传测试2.txt">下载</a>

@RequestMapping("/testFileUpload")
	public String testFileUpload(@RequestParam("file") MultipartFile file, @RequestParam("desc") String desc,
			HttpServletRequest request) throws Exception {
		System.out.println(file.getOriginalFilename());
		// System.out.println(file.getName());
		System.out.println(desc);
		System.out.println(file.getInputStream());

		if (!file.isEmpty()) {
			String contextPath = request.getServletContext().getRealPath("/upload");
			String originalFilename = file.getOriginalFilename();
			File filePath = new File(contextPath);

			if (!filePath.exists()) {
				filePath.mkdirs();
			}

			file.transferTo(new File(contextPath + File.separator + originalFilename));

		} else {
			throw new Exception("请选择上传的文件!");
		}

		return "success";
	}
	
	@RequestMapping("/downloadFile")
	public ResponseEntity<byte[]> downloadFile(HttpServletRequest request, @RequestParam("fileName") String fileName) throws IOException {
		String realPath = request.getServletContext().getRealPath("/upload");
		File downLoadFile = new File(realPath + File.separator + fileName);
		byte[] body = FileUtils.readFileToByteArray(downLoadFile);
		HttpHeaders headers = new HttpHeaders();
		headers.setContentDispositionFormData("attachment", fileName);
		HttpStatus status = HttpStatus.CREATED;
		
		ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(body, headers, status);
		return response;
	}
springMVC.xml
	<!-- 配置MultipartResolver -->
	<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<property name="defaultEncoding" value="UTF-8"></property>
		<property name="maxUploadSize" value="1024000"></property>
	</bean>

pom.xml
<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>1.3.3</version>
		</dependency>



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值