旅游项目(三)ssm实现文件上传下载实操

该博客详细介绍了如何在SSM(Spring、SpringMVC、MyBatis)框架下实现文件上传和下载功能。用户能够通过multipart格式上传文件到服务器,业务层代码进行了具体的操作处理。同时,文章还讲解了如何将保存的文件转换为byte数组以供浏览器下载。
摘要由CSDN通过智能技术生成

用户通过浏览器以multipart格式上传到服务器后,业务层代码:

public boolean uploadObject(String title, MultipartFile mFile) throws IOException {
		//1.判断文件合法
		if(StringUtils.isEmpty(title)) throw new InputInvalidException("标题不能为空");
		if(mFile==null|| mFile.isEmpty()) throw new InputInvalidException("文件对象不能为空");
		//2.计算文件摘要
		String fileDigest = DigestUtils.md5DigestAsHex(mFile.getBytes());
		//3.根据摘要查询数据库
		Attachment attachment = attachmentDao.findObjectByDigest(fileDigest);
                //发现该摘要,则提示已经上传 
               if(attachment!=null) throw new FileUploadException("文件已上传");
		//4.如果木有则执行上传
		//文件夹以日期形式构建
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
		String destDir="d:/upload/"+sdf.format(new Date())+"/";
		//文件名前拼接UUID以防重名
		String newName=UUID.randomUUID().toString();
		String fileName = mFile.getOriginalFilename();
		//取文件格式
		String ext = fileName.substring(fileName.lastIndexOf("."));
		String destFileName=newName+ext;
		//新建文件
		File dest = new File(destDir,destFileName);
		//构建文件夹目录
		File parent = dest.getParentFile();
		if(!parent.exists()) parent.mkdirs();
		mFile.transferTo(dest);
		Attachment newAttachment = new Attachment();
		newAttachment.setTitle(title);
		newAttachment.setFileName(mFile.getName());
		newAttachment.setFilePath(dest.getAbsolutePath());
		newAttachment.setContentType(mFile.getContentType());
		newAttachment.setFileDigest(fileDigest);
		int n = attachmentDao.insertObject(newAttachment);
		if(n!=1) throw new RuntimeException("插入失败!");
		//5.将文件信息写到数据库中
		return true;
	}

和如何将保存好的文件转成byte数组形式返回给浏览器:

@RequestMapping("doDownload")
	@ResponseBody
	public byte[] downloadObjects(String fileDigest,HttpServletResponse response) throws IOException{
		Attachment attachment = attachmentService.findObjectByDigest(fileDigest);
		//设置响应类型和响应头
		response.setContentType("application/octet-stream");
                //设置响应头时要注意中文文件名的处理!!!
               response.setHeader("Content-disposition", "attachment;filename="+URLEncoder.encode(attachment.getFileName(), "utf-8"));
		//根据文件路径获得一个path对象
		Path path = Paths.get(attachment.getFilePath());
		//nio里面另外一个类用来读取path里面的字节数
		return Files.readAllBytes(path);
	}


评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值