`
747017186
  • 浏览: 317619 次
社区版块
存档分类
最新评论

struts2文件的上传与下载

 
阅读更多

前几天做了图片文件的上传,以前虽然也做过但是每次做都要查找资料,现在在这里做个笔记。

我用的是Struts2的图片上传。下面我们来看代码:

前端页面:

<script type="text/javascript" src="${rootPath}/scripts/jquery.form.js"></script>

 

<form action="${rootPath}/plat/knowledgebase/ajaxUploadPicture.htm" method="post" enctype="multipart/form-data" id="pictureform">

 <tr height="60px"> 

         <td class="rigthtext">健康知识图片:</td> 

         <td  class="lefttext">

       <img src="${rootPath}${knowledgeBase.picture}" alt="无法显示" style="width: 200px;" id="showimg"/>

         <input class="input-sousuo" type="file" name="file" style="width: 50%;" onchange="ajaxUploadPicture();" id="upfile"/>

         </td> 

     </tr> 

 </form>

 

/**

 * 检验是否是图片文件

 */

function verifimg(){

var filePath = document.getElementById("upfile");

if(filePath.value!=null && filePath.value.length>0){

//图片比较少且类型固定时

if(!(/(?:jpg|gif|png|bmp|jpeg|tif|tiff)$/i.test(filePath.value))){//只判断jpg|gif|png格式,其他的格式可以往后追加

alert("只支持jpg/gif/png/bmp/jpeg/tif/tiff的图片");

$('#showimg').attr("src","");

return false;

}else{

return true;

}

 

//图片比较多且类型不固定时

<%--if(!(/image\/.*/i.test(filePath.value))){--%>

<%--alert("不是图片类型");--%>

<%--return false;--%>

<%--}else{--%>

<%--return true;--%>

<%--}--%>

}else{

return true;

}

}

 

/**

 * from异步上传图片

点击图片提交的时候,先异步上传图片,把图片在服务器上的路径返回回来

把图片返回的图片路径设置到另一个form里面,把图片路径进行提交,路径存放到数据库

 */

function ajaxUploadPicture(){

if(verifimg()){

var option={

async:true,

cache:false,

dataType:"text",

type:"post",

success: function(data){

   $('#pictureinput').val(data);//设置图片路径

   $('#showimg').attr("src",rootPath+data);//进行预览

}

};

$('#pictureform').ajaxSubmit(option);//图片异步上传,来自于jQuery.form,必须导入相应的jQuery.form.js

}

}

 

后台代码:

/**

* ajax上传图片

* @throws IOException 

*/

private File file;//上传文件,临时文件,最终转换成流写入文件(一般以XXXXX.TEMP.的文件)

private final String basePath="/images/knowledgebase";

public void ajaxUploadPicture() throws IOException{

String newPath=ServletActionContext.getServletContext().getRealPath("/")+basePath;//上传文件在服务器上的路径

if(!new File(newPath).exists()){

new File(newPath).mkdirs();

}

 

//清除服务器上的冗余图片

File [] f=new File(newPath).listFiles();

for(int i=0;i<f.length;i++){

if(f[i].getName().endsWith(".jpg")){//必须是图片

boolean b=knowledgeBaseService.findExitByPic(basePath+"/"+f[i].getName());

System.out.println("##########"+b);

if(!b){//如果数据库里面没有则删除

f[i].delete();

}

}

}

 

String newImage=new IdGenerator().generate()+".jpg";//上传文件的图片名字

newPath=newPath+"/"+newImage;

 

org.apache.commons.io.FileUtils.copyInputStreamToFile(new FileInputStream(file), new File(newPath));//开始上传,把流写入自己新建的文件

this.printToJsp(basePath+"/"+newImage);//回写图片路径

}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics