Java文件的上传和下载(一切皆流)

本文介绍了一个简单的文件上传和下载功能的实现方法。通过Spring框架的@Controller注解处理HTTP请求,实现了文件的批量上传和按需下载。文章详细展示了如何使用MultipartFile处理文件上传,并在服务器指定目录保存文件,同时提供了文件下载的实现方式。

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

一:文件上传

@RequestMapping(value = "batchUpload")
	public void batchUpload(HttpServletRequest req, @RequestParam("file") MultipartFile multipartFile) {

		

		 SimpleDateFormat formattime = new SimpleDateFormat("yyyyMMddHHmmss");
	     String time = formattime.format(new Date());
	     Random random = new Random();
	     int randomint = random.nextInt(100);
	     String fileId = time+String.valueOf(randomint);//id
		try {
			
			if (!multipartFile.isEmpty()) {
				String name = null;// 文件名
				
				String newFileName = null;
				//String fileName = null;
				//String refileName="";
				String fileType="";
				
				
				String uploadDir =uploadconfig.getServerPath();//文件上传地址
				// 创建文件夹  
				File file = new File(uploadDir);    
				if (!file.exists()) {    
					file.mkdirs();    
				}
				//处理long型主键转string防js精度丢失
			
					name = multipartFile.getOriginalFilename();//文件名称
					fileType = FilenameUtils.getExtension(name);//文件类型
					
					newFileName = fileId.concat(".").concat(fileType); //服务器名称
					String nFname = newFileName;
		
					File savedFile = new File(uploadDir, nFname);
					multipartFile.transferTo(savedFile);

				
				
			}else {
				
			}
		
		} catch (Exception e) {
			e.printStackTrace();
		
			  
		}
	}

二:文件下载

		@RequestMapping(value="/downloadFile")  
	public void downloadFile(String pathname,String ServerName,HttpServletResponse response,HttpServletRequest request) throws Exception {

				String dir = uploadconfig.getServerPath();//下载地址
				String path = dir+"/"+pathname;		//下载地址+名称
				System.out.println("这是下载地址加名称------------:"+path);
                File file=new File(path);
                boolean exists = file.exists();
                System.out.println("是否有该文件:"+exists);
                if (exists) {
                    response.setCharacterEncoding("utf-8");
                    response.setContentType("text/plain");
                    //解决中文乱码
                    try {
    					response.setHeader("Content-Disposition","attachment;filename="+new String("下载后的名称".getBytes("utf-8"),"iso-8859-1"));
    				} catch (UnsupportedEncodingException e) {
    					// TODO Auto-generated catch block
    					e.printStackTrace();
    				} 
                   // FileInputStream fis=new FileInputStream(file);
                   // BufferedInputStream buff=new BufferedInputStream(fis);
              InputStream in =  new FileInputStream(file);
              ServletOutputStream os =  response.getOutputStream();
              int len;
              byte [] b=new byte[1024];//
              while((len=in.read(b))!=-1){
            	  os.write(b,0,len);
              }
              
              os.close();
              in.close();
			}else {
				    System.out.println("该路径下没有该文件:"+path);
			}
            
         
    }

笔记!勿喷

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值