Java中图片以虚拟路径形式存储到数据库

//上传文件
	public void uploadImg(MultipartFile[] multipartFiles){
		for(int i=0;i<multipartFiles.length;i++) {
			 GenerateImage(multipartFiles[i]);
		}
	}
	public boolean GenerateImage(MultipartFile multipartFile) {
		// 判断图像数据为空
		String name =multipartFile.getOriginalFilename();
		String fileExt = name.substring(name.lastIndexOf(".") + 1).toLowerCase();
		try {
			// 生成图片
			InputStream inputStream = multipartFile.getInputStream();
			SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
			String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
			byte[] bs = new byte[1024];
			PropertiesLoader loader = new PropertiesLoader("filePath.properties");
			String filePath = loader.getProperty("filePath");
			File saveDirFile = new File(filePath+"/uploadImg");
			if (!saveDirFile.exists()) {
				saveDirFile.mkdirs();
			}
			String imgFilePath = saveDirFile.getPath() +"/"+ newFileName;
			int len;
			OutputStream out = new FileOutputStream(imgFilePath);
			while ((len = inputStream.read(bs)) != -1) {
				out.write(bs, 0, len);
			}
			out.flush();
			out.close();
			AppImage appImage = new AppImage();
			//Global.USERFILES_BASE_URL此处为虚拟路径"/userfiles/"
			String savePath = Global.USERFILES_BASE_URL+"uploadImg/"+newFileName;
			appImage.setUrl(savePath);
			appImage.setDelFlag("0");
			appImage.preInsert();
			uploadDao.insert(appImage);
			return true;
		} catch (Exception e) {
			return false;
		}
	}

此处需要配置文件中定义filePath=D:\files路径

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值