以下是开发中的部分代码,可能并不全,但是起码可以知道思路是什么样的。
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"/>