struts上传文件至数据库

以下是开发中的部分代码,可能并不全,但是起码可以知道思路是什么样的。

public PicAttachment addAttachment(FormFile f) throws TSDBException, FileNotFoundException, IOException {
		PicAttachment pic = new PicAttachment();
		pic.setContenttype(f.getContentType());
		pic.setFilesize(new Long(f.getFileSize()));
		pic.setUploaddate(new Date());
		// 上传文件实体类名
		pic.setUploadType("JzglAllotInfoWz");
		// 原文件名
		pic.setRealFilename(f.getFileName());
                //作为byte数组放入数据库中
		pic.setUploadFile(f.getFileData());
		pic.setUseFlag(new Long(Constants.USE_FLAG.USE_FLAG_ON.longValue()));

		String filePath = ConfigPath.getRootPath("picPath");
		String newPath = "bjjz/";
		String fileName = FileUtils.getRandomFileName(f.getFileName());
		boolean isTrue = copyFile(f, filePath + newPath, fileName, pic);
		pic.setFilename(newPath + fileName);
		if (!isTrue) {
			// throw new TSDBException("Upload file Error");
		}
		return pic;
	}

protected static boolean copyFile(FormFile file, String path, String fileName, PicAttachment pic) {
		try {
			InputStream stream = file.getInputStream();
			OutputStream bos = new FileOutputStream(path + fileName);
			FileCollection excahngeFile = new FileCollection(fileName, "bjjz/");
			stream = excahngeFile.addFile(stream);
			int bytesRead = 0;
			byte[] buffer = new byte[10240];
			while ((bytesRead = stream.read(buffer)) != -1) {
				bos.write(buffer, 0, bytesRead);
			}
			// pic.setUploadFile(buffer);
			bos.close();
			stream.close();
			// 数据交换
			ExcahngeUitl.post(excahngeFile, DataPost.SAVE_FILE);
			return true;
		} catch (Exception e) {
			Logger.error("Write file error ! " + e.getMessage());
		}
		return false;
	}

 

public class FileCollection implements Serializable {

	private String name; //文件名 
	private String prefixPath;  //文件前缀路径
	private byte bata[];

    /**
     * 设置文件信息
     * @param fileName 文件名
     * @param prefixPath 文件前缀路径
     * @throws IOException
     */
	public FileCollection(String fileName,String prefixPath) throws IOException {
		name = fileName;
		this.prefixPath=prefixPath;
	}
	
	/**
	 * 添加文件流
	 * @param stream 输入流
	 * @throws IOException
	 */
	public InputStream addFile(InputStream stream) throws IOException{
		bata = FileUtils.toByteArray(stream);
		return stream= new ByteArrayInputStream(ArrayUtils.clone(bata));
	}

 hibernate对于上传文件的配置方式:

<property column="UPLOADFILE" length="4000" name="uploadFile" type="com.topsuntech.gOS.query.type.OracleBlobType" not-null="false"/>

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值