java上传图片到文件夹

来源:互联网 发布:中科软件 董事长 编辑:程序博客网 时间:2024/05/29 03:14

目的:上传本地图片到服务器的指定文件夹中


第一步:编写前端代码

核心代码还是用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,这样就可以实现上传图片的功能了。

0 0
原创粉丝点击