上传文件时用二进制存取数据库,以及文件上传

1、Action类:
public class EnterpriseAction  extends BaseAction {
   //此方法主要是将数据库里文件二进制转为文件存放在服务器某路径下
   public void initorgimg(ScFile file,String reqattr){
HttpServletRequest request = getRequest();
// 获取存放路径
String savePath = ServletActionContext.getServletContext().getRealPath("/");
savePath = savePath.replace("\\", "/");
String filepath = savePath + file.getFilename();
//判断路径下是否存在此图片

  File existFile = new File(filepath); //此处为你要判断的地址,
  if(!existFile.exists()){//如果该图片文件不存在

  FileUtil.base64StringToFile(file.getContent(), filepath);
  }
  request.setAttribute(reqattr, filepath.substring(filepath.indexOf("/UploadImages"))); //这里是去除根目录,获得相对路径
}
    //页面显示图片的action
public String eorglist(){

ScEuseracct user = (ScEuseracct) getRequest().getSession().getAttribute("ScEuseracct");
DetachedCriteria dc=DetachedCriteria.forClass(ScEcertinfo.class,"bc");
dc.add(Restrictions.eq("bc.scEuseracct.id", user.getId()));
list=service.findAllByCriteria(dc);
if(list!=null&&list.size()>0){
ecertinf=(ScEcertinfo)list.get(0);
if(ecertinf.getOrgchartaid()!=null&&!"".equals(ecertinf.getOrgchartaid())){
ScFile file1=(ScFile)service.get(ScFile.class, ecertinf.getOrgchartaid());
if(file1!=null){
initorgimg(file1,"file1");
}
}
}
       return SUCCESS;
}
//从页面获得的文件存入数据库
public String eorgsave(){
ecertinf=new ScEcertinfo();
ecertinf.setAdddate(new Date());
String res = service.saveorg( f1, f1FileName, ecertinf);
if ("00".equals(res)) {
return SUCCESS;
}
if ("01".equals(res)) {
setMessage("<script>alert(\"请上传组织机构资料!\");history.go(-1);</script>");
return ERROR;
}
if ("05".equals(res)) {
setMessage("<script>alert(\"系统异常,请稍后再试!\");history.go(-1);</script>");
return ERROR;
}
if ("06".equals(res)) {
setMessage("<script>alert(\"上传图片异常,请稍后再试!\");history.go(-1);</script>");
return ERROR;
}
if ("07".equals(res)) {
setMessage("<script>alert(\"请上传图片类型!\");history.go(-1);</script>");
return ERROR;
}

return SUCCESS;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return ERROR;
}
}
}

2、service层:
public class EnterpriseServiceImpl implements IEnterpriseService {
   public String saveorg( File f1, String f1FileName, ScEcertinfo certinfo) {
try {

if ((f1FileName == null || f1.length() == 0){ return "01";
} String type1=null;
if(f1FileName!=null&&!"".equals(f1FileName)){
type1=getFileContentType(f1);
if ("ex".equals(type1)) {
return "06";
}
if (!"img".equals(type1)) {
return "07";
}
}
//上传至服务器并保存到数据库
if(f1FileName!=null&&StringUtil.isNotBlank(type1)){
Long res1 = saveFile(f1, f1FileName, type1);
if (res1 != null) { certinfo.setOrgchartaid(res1);
}else {
return "03";
}
}
certinfo.setFlag("0");   //已添加
saveOrUpdate(certinfo);
return "00";
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "05";
}
}
// 此方法判断文件类型
private String getFileContentType(File f) {

try {

String contentype = FileUtil.getContentTypeByStream(f);
if ("jpg".equals(contentype) || "png".equals(contentype) ) {
return "img";
} else if ("doc".equals(contentype)|| "docx".equals(contentype) || "xls".equals(contentype)|| "xlsx".equals(contentype)|| "pdf".equals(contentype) ) {
return "wxp";
}else{
return "untype";
}

} catch (Exception e) {
e.printStackTrace();
return "ex";
}
}

/**
* 保存文件到数据库,并上传至服务器
*
* @param f
* @param fileame
* @return
*/
public Long saveFile(File f, String ffilename, String filetype) {
// 得到文件名字
try {
String filename = Fileupload.getFileName(f, ffilename);
ScFile file = new ScFile();
file.setContent(FileUtil.getImageBinary(f)); // 这个类型在数据库里是clob类型
file.setContenttype(filetype);// 保存文件类型
file.setIsvalid("1");// 有效
file.setFilename( "/UploadImages/" + "enterprise" + "/" + filename);
file.setCreatetime(StringUtil.getSystemDate());
save(file);
Fileupload.uploads(f, ffilename, "enterprise",filename);
return file.getId();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}

3、工具类

//文件与二进制相互转换的工具类
public class FileUtil {
static BASE64Encoder encoder = new sun.misc.BASE64Encoder();
static BASE64Decoder decoder = new sun.misc.BASE64Decoder();

/**
* 得到base64string存入数据库
*
* @param filepath
* @return
*/
public static String getBinary(String filepath) {
FileInputStream fileinputstream = null;
try {
String content = "";
File binaryFile = new File(filepath);
fileinputstream = new FileInputStream(binaryFile);
int lenght = fileinputstream.available();
byte bytes[] = new byte[lenght];
fileinputstream.read(bytes);
return encoder.encodeBuffer(bytes).trim();
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
} finally {
if (fileinputstream != null) {
try {
fileinputstream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

}

/**
* 将base64String转为文件
*
* @param base64String
* @param filepath
*/
public static void base64StringToFile(String base64String, String filepath) {
FileOutputStream fstream = null;
BufferedOutputStream stream = null;
try {
byte[] bytes1 = decoder.decodeBuffer(base64String);
File file = new File(filepath);
fstream = new FileOutputStream(file);
stream = new BufferedOutputStream(fstream);
stream.write(bytes1);// 调试到这里文件已经生成
stream.close();
fstream.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭流
if (fstream != null) {
try {
fstream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//*************************以下两个方法是专门针对的图片的转换,通常情况下用上面两种通用方法即可*******************
// 将二进制转为图片,只适用于图片
public static void base64StringToImage(String base64String, String filepath) {
ByteArrayInputStream bais = null;
BufferedImage bi1 = null;
try {
if (StringUtil.isNotBlank(base64String)) {
byte[] bytes1 = decoder.decodeBuffer(base64String);
bais = new ByteArrayInputStream(bytes1); bi1 = ImageIO.read(bais);

File w2 = new File(filepath);// 可以是jpg,png,gif格式
ImageIO.write(bi1, "jpg", w2);// 不管输出什么格式图片,此处不需改动
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bais != null) {
try {
bais.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (bi1 != null) {
bi1 = null;
}
}
}

/**
* 通过页面传进来的图片得到二进制文件,只适用于图片
*
* @param f
* @return
*/
public static String getImageBinary(File f) {
ByteArrayOutputStream baos = null;
try {
BufferedImage bi = ImageIO.read(f);
baos = new ByteArrayOutputStream();
ImageIO.write(bi, "jpg", baos);
byte[] bytes = baos.toByteArray();
return encoder.encodeBuffer(bytes).trim();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (baos != null) {
try {
baos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}

/**
* 判断文件类型
*
* @param is
* @return
*/
public static String getContentTypeByStream(File f) {
FileInputStream is = null;
String type = "";
byte[] b = new byte[4];
try {
is = new FileInputStream(f);
is.read(b, 0, b.length);

type = bytesToHexString(b).toUpperCase();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}

}
if (type.contains("FFD8FF")) {
return "jpg";
} else if (type.contains("89504E47")) {
return "png";
} else if (type.contains("47494638")) {
return "gif";
} else if (type.contains("49492A00")) {
return "tif";
} else if (type.contains("424D")) {
return "bmp";
}else if (type.contains("D0CF11E0")) {
return "doc";
}
else if (type.contains("255044462D312E")) {
return "pdf";
}
else if (type.contains("504b0304140006000800")) {
return "docx";
}if (type.contains("504B030414000600080000002100")) {
return "xlsx";
}
return type;
}

/**
* byte数组转换成16进制字符串
*
* @param src
* @return
*/
public static String bytesToHexString(byte[] src) {
StringBuilder stringBuilder = new StringBuilder();
if (src == null || src.length <= 0) {
return null;
}
for (int i = 0; i < src.length; i++) {
int v = src[i] & 0xFF;
String hv = Integer.toHexString(v);
if (hv.length() < 2) {
stringBuilder.append(0);
}
stringBuilder.append(hv);
}
return stringBuilder.toString();
}
}

//文件上传类

public class Fileupload {
public static String uploads(File fileupload, String fileuploadFileName, String folderName,String newFileName ) {
HttpServletResponse response = ServletActionContext.getResponse();
response.setCharacterEncoding("GBK");
if (fileupload != null) {
try {
// 获取存放路径
String savePath = ServletActionContext.getServletContext().getRealPath("/UploadImages/" + folderName + "/") + "/" + newFileName;

savePath = savePath.replace("\\", "/");
File imageFile = new File(savePath);
FileUtils.copyFile(fileupload, imageFile); //这里的FileUtils为:org.apache.commons.io.FileUtils
return "/UploadImages/" + folderName + "/" + newFileName;

} catch (IOException e) {
e.printStackTrace(); return "01";
}

} else {
return "01";
}
}
public static String getFileName(File fileupload, String fileuploadFileName) {
String extName = ""; // 保存文件拓展名
String newFileName = ""; // 保存新的文件名
String nowTimeStr = ""; // 保存当前时间
SimpleDateFormat sDateFormat;
Random r = new Random();
HttpServletResponse response = ServletActionContext.getResponse();
response.setCharacterEncoding("GBK");
// 生成随机文件名:当前年月日时分秒+五位随机数(为了在实际项目中防止文件同名而进行的处理)
int rannum = (int) (r.nextDouble() * (999 - 100 + 1)) + 100; // 获取随机数
sDateFormat = new SimpleDateFormat("yyyyMMdd"); // 时间格式化的格式
nowTimeStr = sDateFormat.format(new Date()); // 当前时间
// 获取拓展名
if (fileupload != null) {
if (fileuploadFileName.lastIndexOf(".") >= 0) {

extName = fileuploadFileName.substring(fileuploadFileName.lastIndexOf("."));
}
// 文件重命名后的名字
newFileName = nowTimeStr + rannum + extName;
return newFileName;

} else {
return "01";
}
}

}

猜你喜欢

转载自bingdongsanxian.iteye.com/blog/2238807