java上传图片到文件夹
2015-10-17 22:13
686 查看
目的:上传本地图片到服务器的指定文件夹中
iframe 中会显示上传成功后的图片预览
OK,这样就可以实现上传图片的功能了。
第一步:编写前端代码
核心代码还是用form表单提交数据,传入action中<form id="form_picupload" action="upLoadPic.action" method="post" target="imageUpload" enctype="multipart/form-data"> <span><input type="file" onchange="picUplod();" name="upload" id="input_file">推荐尺寸:。。。</span> <input type="hidden" name="uploadType" id="uploadType" value="carimg" style="display: none;"> <input class="onlo" type="submit" name="submit" value="上传" style="margin:10px 70px;"/> </form> <iframe id="imageUpload" name="imageUpload" src="about:blank" style="margin-left:170px;display: none;"></iframe>
iframe 中会显示上传成功后的图片预览
第二步:后台Action中的代码
// 封装上传文件域的属性 private File upload; // 封装上传文件类型的属性 private String uploadContentType; private String uploadType; // 封装上传文件名的属性 private String uploadFileName; //这里是上面一些属性的getter和setter方法。。。 //。。。 //上传图片的程序 public void upLoadPic(){ String folder = uploadType; String loadpath = request.getSession().getServletContext().getRealPath("/") + folder; // 上传文件存放目录 if(!(new File(loadpath).isDirectory())){ new File(loadpath).mkdir(); } FileOutputStream fos = null; FileInputStream fis = null; String name = ""; try { //以服务器的文件保存地址和原文件名建立上传文件输出流 name = getUploadFileName(); fos = new FileOutputStream(loadpath + "/" + name); //以上传文件建立一个文件上传流 fis = new FileInputStream(getUpload()); //将上传文件的内容写入服务器 byte[] buffer = new byte[1024]; int len = 0; while ((len = fis.read(buffer)) > 0) { fos.write(buffer , 0 , len); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); }finally{ try { if(fos != null) fos.close(); if(fis != null) fis.close(); } catch (IOException e) { e.printStackTrace(); } //将图片写到前端显示预览图 write("<script>parent.updatePic('" + this.contextPath + "/"+folder+"/" + name + "');</script>"); }
OK,这样就可以实现上传图片的功能了。
相关文章推荐
- java解释器模式
- java中介者模式
- java访问者模式
- java中URLEncode和URLDecode
- java状态模式
- JDK高性能编程之多线程
- Java基础----Java容器之集合
- Eclipse快捷键大全
- Android Studio 使用日志:2.升级 JDK 后,Android Studio 启动编译报错的解决方法
- static_隐式参数_继承_重写_toString_组合JAVA036-042
- spring beans源码解读
- Java单例模式之饿汉模式与懒汉模式
- Java单例模式之饿汉模式与懒汉模式
- Java中HashTable和ConcurrentHashMap的区别
- 八张图理解Java
- Spring配置文件详解
- spring IOC源码分析(1)
- spring IOC源码分析(2)
- Java IO2:RandomAccessFile
- java中url中文编码问题