Ext中的文件上传笔记,呵呵!
话还得从头说起,因为这一段时间以来我们公司正在用ext来做后台的管理系统,而我做的那一块里面包含了一个照片上传的功能 ,
因为对ext还不是太熟,所以以为它其中的文件上传控件还要自己去重写它的控件,可没想到上一下它的论坛一搜,原来只要在控件
里面将其xtype设置为file,再将form里面的fileUpload设置为true就行了,这时以为问题解决了,就在action里面用String来接收上传
控件里面的内容,可是搞了大半天还是收不到啥东西,后来经师兄点醒才知道原来直接用file对象接收就行了(晕,当然,这不是ext
的问题,是我自己菜的原因)。
用file对象接收后我采用了一个同事的建议将其转化成字节流后存入一个字节数组然后再存入数据库,(因为对java中的图像操作不熟,所以也搞了一点时间,)
不过后来还是搞定了:
这是转化后保存的代码:
public void save() throws Exception{logger.debug("id:" + student.getId()); logger.debug("photo:" + (photoObj==null));HashMap<String, Object> result = this.getDefaultMap();List<Student> list = new ArrayList<Student>();try{if(photoObj!=null){ logger.debug("here:"); BufferedImage img=ImageIO.read(photoObj); int h = img.getHeight(); int w = img.getWidth();byte[] data = new byte[h*w];ByteArrayOutputStream out = new ByteArrayOutputStream();BufferedImage dest = new BufferedImage(w, h,BufferedImage.TYPE_3BYTE_BGR);dest.getGraphics().drawImage(img, 0, 0, w, h, Color.WHITE,null);JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);encoder.encode(dest);data = out.toByteArray();logger.debug("data.length:" + data.length);student.setPhoto(data);String outname="c:\\\\img3.jpg";FileOutputStream fileoutputstream = new FileOutputStream(outname); fileoutputstream.write(data); fileoutputstream.close(); out.close();studentManager.save(student);list.add(student);result.put(COUNT, 1);result.put(LIST, 1);}} catch (VersionException se){result.put(SUCCESS, false);result.put(MESSAGE, "该数据已被其他用户修改,请重新加载编辑窗口.");}catch (Exception se){result.put(SUCCESS, false);result.put(MESSAGE, "Error unknown.");}this.getResponse().flushBuffer();outJson(result);}这里是读出到网页的代码:public void image()throws Exception { String id=data.get("myid"); System.out.println("id:"+id); if(id!=null) { Long lid=Long.valueOf(id); //设置浏览器不缓存图片this.getResponse().setHeader("Pragma","No-cache");this.getResponse().setHeader("Cache-Control","no-cache");this.getResponse().setDateHeader("Expires", 0);this.getResponse().addHeader("Content-disposition", "inline" + "; filename=\"" + "safs.jpg" + "\"");this.getResponse().setContentType("image/jpeg");OutputStream os=this.getResponse().getOutputStream();byte[] mybyte=studentManager.getObject(lid).getPhoto();os.write(mybyte);os.close(); } else { logger.debug("This record there isn't photo!"); }}搞定后听另外一个同事说可以直接用一种叫Blob的类型来接收后直接写入数据库就行了,刚好那里要下班了所以就
没去试,不过后来回宿舍后自己试了一下,还真的可以,比先转化成字节流再写入来得直接点。不过因为我们用的pgsql数据库,不支持
Blob,所以我还是决定用bytea来存byte[]算了,以后有机会再用Blob来存吧,呵呵:
以下是我用mysql试验一下的代码:
import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.InputStream;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;public class Dbtest {private static final String URL = "jdbc:mysql://localhost:3306/jiejie?user=root&password=&useUnicode=true"; private Connection conn = null; private PreparedStatement pstmt = null; private ResultSet rs = null; private File file = null; /** * 向数据库中插入一个新的BLOB对象(图片) * @param infile 要输入的数据文件 * @throws java.lang.Exception */ public void blobInsert(String infile) throws Exception { FileInputStream fis = null; try { Class.forName("org.gjt.mm.mysql.Driver").newInstance(); conn = DriverManager.getConnection(URL); file = new File(infile); fis = new FileInputStream(file); pstmt = conn.prepareStatement("insert into tmp(descs,pic) values(?,?)"); pstmt.setString(1,file.getName()); //把传过来的第一个参数设为文件名 pstmt.setBinaryStream(2,fis,fis.available()); //第二个参数为文件的内容 pstmt.executeUpdate(); } catch(Exception ex) { System.out.println("[blobInsert error : ]" + ex.toString()); } finally { //关闭所打开的对像// pstmt.close(); fis.close(); conn.close(); } } /** * 从数据库中读出BLOB对象 * @param outfile 输出的数据文件 * @param picID 要取的图片在数据库中的ID * @throws java.lang.Exception */ public void blobRead(String outfile,String picName) throws Exception { FileOutputStream fos = null; InputStream is = null; byte[] Buffer = new byte[4096]; try { Class.forName("org.gjt.mm.mysql.Driver").newInstance(); conn = DriverManager.getConnection(URL); pstmt = conn.prepareStatement("select pic from tmp where descs=?"); pstmt.setString(1,picName); //传入要取的图片的ID rs = pstmt.executeQuery(); rs.next(); file = new File(outfile); if(!file.exists()) { file.createNewFile(); //如果文件不存在,则创建 } fos = new FileOutputStream(file); is = rs.getBinaryStream("pic"); int size = 0; while((size = is.read(Buffer)) != -1) { //System.out.println(size); fos.write(Buffer,0,size); } } catch(Exception e) { System.out.println("[OutPutFile error : ]" + e.getMessage()); } finally { //关闭用到的资源 fos.close(); rs.close(); pstmt.close(); conn.close(); } } public static void main(String[] args) { try { Dbtest blob = new Dbtest(); //blob.blobInsert("C:/jie1.jpg"); blob.blobRead("c:/1.jpg","jie.jpg"); } catch(Exception e) { System.out.println("[Main func error: ]" + e.getMessage()); } }}