SpringMVC实现文件上传与下载


前言


一、文件上传

	SpringMVC已经帮我们写好了文件上传的处理类,我们只需跟着步骤该一下路径写即可
	1. 导入依赖
		<dependency>
		<groupId>commons-fileupload</groupId>
		<artifactId>commons-fileupload</artifactId>
		<version>1.3.1</version>
		</dependency>
	2.SpringMVC配置文件中装配文件上传的处理类
		<!--SpringMVC已经帮我们写好了文件上传,我们直接使用即可,默认是不开启的-->
    	<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
	    	<!--        默认是byte字节大小计算,1M=1024KB 1KB=1024byte-->
	        <property name="maxUploadSize" value="5242880"/>
	        <property name="defaultEncoding" value="utf-8"/>
    	</bean>
	3.  前台页面
		<h1>文件上传</h1>
		<form action="/file/upload" method="post" enctype="multipart/form-data">
		    选择文件:<input type="file" name="file"><br>
		    <button type="submit">上传</button>
		</form>
	4. 控制器处理流程
		@Controller
		@RequestMapping("/file")
		public class FileController {
		    @RequestMapping("/upload")
		    public String fileUpload(MultipartFile file, HttpServletRequest request){
		        //获取真实上传文件名称
		        String realFileName=file.getOriginalFilename();
		        //上传的文件多,防止重名被覆盖文件
		        String fileName= UUID.randomUUID().toString().replace("-","")+realFileName.substring(realFileName.lastIndexOf("."));
		        //文件保存路径
		        String savePath = request.getServletContext().getRealPath("/upload")+"/";
		        try {
		            //上传
		            file.transferTo(new File(savePath+fileName));
		            System.out.println("上传成功到===>"+savePath);
		        } catch (IOException e) {
		            e.printStackTrace();
		        }
		        return "success";
		    }
		}
	5. 指定上传文件类型
		public class FileTypeInterceptor implements HandlerInterceptor {
	    @Override
	    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
	        boolean flag=true;
	        if(request instanceof MultipartHttpServletRequest){
	            MultipartHttpServletRequest multipartHttpServletRequest=(MultipartHttpServletRequest)request;
	            Map<String, MultipartFile> fileMap = multipartHttpServletRequest.getFileMap();
	            Iterator<String> iterator = fileMap.keySet().iterator();
	            while (iterator.hasNext()){
	                String key=iterator.next();
	                System.out.println("key===>"+key);
	                MultipartFile file = multipartHttpServletRequest.getFile(key);
	                String originalFilename = file.getOriginalFilename();
	                String type = originalFilename.substring(originalFilename.lastIndexOf("."));
	                System.out.println("上传的文件类型===>"+type);
	                if(!type.toLowerCase().equals(".jpg") && !type.toLowerCase().equals(".png")){
	                    request.getRequestDispatcher("/fileType.jsp").forward(request,response);
	                    flag=false;
	                }
	            }
	        }
	        return flag;
	    }
	}

二、文件下载

	1. 控制器
		@RequestMapping("/download")
	    public ResponseEntity<byte[]> download(HttpServletRequest request) throws IOException {
	        //指定下载文件路径
	        String path=request.getServletContext().getRealPath("/upload")+"/c4faeb4210004decbde44dc5bfef80f3.png";
	        //创建响应的 头信息 对象
	        HttpHeaders httpHeaders = new HttpHeaders();
	        //标记以流的方式响应
	        httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
	        //以附件的形式响应给用户
	        httpHeaders.setContentDispositionFormData("attachment", URLEncoder.encode("c4faeb4210004decbde44dc5bfef80f3.png","utf-8"));
	        File file=new File(path);
	        ResponseEntity<byte[]> responseEntity=new ResponseEntity<>(FileUtils.readFileToByteArray(file),httpHeaders,HttpStatus.CREATED);
	        return responseEntity;
	    }

总结

提示:完结

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值