使用base64把图片存到数据库中和下载

response.setContentType("application/x-download;charset=utf-8");
					String filenameDisplay = URLEncoder.encode(fileFileName,"UTF-8");
					  response.addHeader("Content-Disposition","attachment;filename=" + filenameDisplay );
					ServletOutputStream out=response.getOutputStream();
					   out.write(bytes1);

 把上面的代码替换下面的return这一行就可以进行下载

public class TestImageBinary {
	static BASE64Encoder encoder = new sun.misc.BASE64Encoder();    
    static BASE64Decoder decoder = new sun.misc.BASE64Decoder();    
        
    public static void main(String[] args) {    
        System.out.println(getImageBinary());    
            
        base64StringToImage(getImageBinary());    
    }    
        
    static String getImageBinary(){    
        File f = new File("D:\\workspance2\\.metadata\\.plugins\\org.eclipse.wst.server.core\\tmp0\\wtpwebapps\\idz_cassandra\\demo\\mobilebg.png");           
        BufferedImage bi;    
        try {    
            bi = ImageIO.read(f);    
            ByteArrayOutputStream baos = new ByteArrayOutputStream();    
            ImageIO.write(bi, "png", baos);    
            byte[] bytes = baos.toByteArray();    
                
            return encoder.encodeBuffer(bytes).trim();    
        } catch (IOException e) {    
            e.printStackTrace();    
        }    
        return null;    
    }    
        
    static void base64StringToImage(String base64String){    
        try {    
            byte[] bytes1 = decoder.decodeBuffer(base64String);    
                
            ByteArrayInputStream bais = new ByteArrayInputStream(bytes1);    
            BufferedImage bi1 =ImageIO.read(bais);    
            File w2 = new File("c://QQ.png");//可以是jpg,png,gif格式    
            ImageIO.write(bi1, "jpg", w2);//不管输出什么格式图片,此处不需改动    
        } catch (IOException e) {    
            e.printStackTrace();    
        }    
    }   
}

 

 

你可能感兴趣的:(数据库,开发工具)