`
wytkings
  • 浏览: 6362 次
  • 性别: Icon_minigender_1
  • 来自: 厦门
最近访客 更多访客>>
文章分类
社区版块
存档分类
最新评论

读取sql server中二进制图片

阅读更多
public void showPhoto(HttpServletResponse response,String fphotoId){
    Connection conn = null;
    try{
    try {
    InitialContext ic = new InitialContext();
    Statement stmt = null;
    conn = DBConnection.getConnection();
    BufferedInputStream inputimage = null;
    stmt = conn.createStatement();
    boolean defaultCommit = conn.getAutoCommit();
    conn.setAutoCommit(false);
    ResultSet rs = stmt.executeQuery("SELECT * FROM t_photo WHERE fid='"+ fphotoId + "'");
    if (rs.next()) {
    Blob blob = (Blob) rs.getBlob("fimage");
    long size = blob.length();
    byte[] bs = blob.getBytes(1, (int) size);
    response.setContentType("image/jpeg;charset=GB2312");
    response.setHeader("Content-Transfer-Encoding", "base64");
    String filepath = "";
    String dir = this.getServlet().getServletContext().getRealPath("UPLOAD");
    File dirFile = new File(dir);
    if (!(dirFile.exists()) && !(dirFile.isDirectory())) {
    dirFile.mkdir();
    }
    String filename = getRndFileName("jpg");
    filepath = fphotoId+ filename.substring(filename.lastIndexOf("."),filename.length());
    OutputStream out1 = new FileOutputStream(dir + "\\" + filepath);
    out1.write(bs, 0, bs.length);
    out1.close();
    rs.close();
    } else {
    rs.close();
    }
    } catch (Exception e) {
    conn.rollback();
    e.printStackTrace();
    } finally {
    conn.close();
    }
    }catch(Exception e){
    e.printStackTrace();
    }
    }

/**
* @param path
* @return 返回随机获得的文件名 获取随机文件名.如 aa.gif bb.jpg 等.
*/
public String getRndFileName(String path) {
String rndFileName = String.valueOf(System.currentTimeMillis())
+ String.valueOf(new Random().nextInt(100));
String extFileName = getExName(path);
if (!extFileName.equals("")) {
rndFileName = rndFileName + "." + extFileName;
}
return rndFileName;
}

// 获取文件扩展名.如: gif jpg (不包括".")等.
public String getExName(String path) {
int strint = path.lastIndexOf(".");
return path.substring(strint + 1);// 这样是不包括点
// return path.substring(strint);//这样是有包括点
}

将读取的图片上传到服务器中。。。。
if(productList.size() != 0){
    for (Product product : productList) {
    if(product.getPhoto() != null){
    String fphotoid = product.getPhoto().getFid();
    String filepath = "";
    String dir = this.getServlet().getServletContext().getRealPath("UPLOAD");
    filepath = dir + "\\"+fphotoid+".jpg";
    File file = new File(filepath);
    if(!file.exists()){
    showPhoto(response,fphotoid);
    }
    }
}
    request.setAttribute("productList",productList);
    }
1
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics