1.在Java项目中上传图片时如何使上传的图片自动保存到指定路径
用struts也可以实现 多文件上传 下面是我写的代码,参数中有要保存的目录 作为参考!/*文件目录*/ public static String [] fileArray={ "logo.png", "index.swf", "OEMInfo.txt", "favicon.ico"};/** * @author Caoshun * @see 接收并保存文件 * */ public static void (ActionForm form,String rootPath1,String rootPath2){ String fileName=""; //获取表单中的文件资源 Hashtable
//文件名 //String fileName = file.getFileName(); //System.out.println("debug in AddEnterpriceAction.java on line 152 fileName is : "+fileName); //文件大小 //int fileSize = file.getFileSize(); //文件流 InputStream is = file.getInputStream(); //将输入流保存到文件 //String rootPath = this.servlet.getServletContext().getRealPath("files"); //往cn中写入 File rf = new File(rootPath1); FileOutputStream fos = null; fos = new FileOutputStream(new File(rf, fileName)); byte[] b = new byte[10240]; int real = 0; real = is.read(b); while (real > 0) { fos.write(b, 0, real); real = is.read(b); } //往en中写入 File rf2 = new File(rootPath2); InputStream is2 = file.getInputStream(); FileOutputStream fos2 = null; fos2 = new FileOutputStream(new File(rf2, fileName)); byte[] b2 = new byte[10240]; int real2 = 0; real2 = is2.read(b2); while (real2 > 0) { fos2.write(b2, 0, real2); real2 = is2.read(b2); } //关闭文件流 fos.close(); is.close(); fos2.close(); is2.close(); } catch (RuntimeException e1) { e1.printStackTrace(); } catch (Exception ee) { ee.printStackTrace(); } file.destroy(); } file_num++; } }。
2.图片该如何存储在数据库里面,存放路径好还是以二进制存放在数据库
从项目的角度上来说,图片存储和数据库存储都是必须要分离的,
否则这一个模块就能拖垮你的整个工程。
二进制的存储方式,已经淘汰了,性能非常差,在以后的数据库版本里已经取消了这个存储方式。
存放路径,是一种非常方便的解决方案,不存在什么其他的问题,容易管理。
比如,你以前用二进制存储的一个图片,又要IO又要缓存的才能展示给用户看。
现在你保存的是地址,仅仅需要把链接提取出来即可,这样减少了数据访问上的压力。