java文件上传(文件大小校验)、下载、删除的实现代码

来源:互联网 发布:淘宝二手电脑店铺推荐 编辑:程序博客网 时间:2024/06/06 03:33

最近做了一个附件上传下载删除的功能,特地把关键代码记录下来,方便以后复用,也分享给大家!

首先是JSP 代码:

        <td class="tdHead33">附件上传:<br/><font color="red"><b>(提示:单个文件上传不得超过10M)</b></font></td> <td id="accessoryFileTd"><a onclick="addFile()">添加附件</a><br/>                <!-- 循环出已经上传的附件 -->                 <s:iterator value="signFileList"  id="file"  status="st1"> <div id="accessoryDiv<s:property value="#st1.index"/>" style="padding:3px"> <a onclick="javascript:exportSingle('<s:property value="#file.FILE_URL"/>')" > <s:property value='#file.FILE_NAME'/>  </a>  <a  onclick="deleteFile('accessory','<s:property value="#file.FILE_URL"/>','<s:property value="#st1.index"/>')"  class="Edit_Button" href="javaScript:void(0);">         删除 </a>  </div>  </s:iterator>       </td> 


然后是JS代码: 

文件上传成功后,保存到数据库中的FILE_URL文件路径是文件路径+文件名称+时间戳,删除和下载都是根据FILE_URL唯一确定的。

         var fileNum=1;         // 增加附件上传控件         function addFile(){var str="<div id=\"fileDiv"+fileNum+"\"> ";str+="<input id=\"accessoryFile\" name=\"formBean.accessoryFile\" type=\"file\"/> ";str+="  <a id=\"delete\" onclick=\"deleteFile("+fileNum+")\" style=\"text-decoration:underline\">删除</a>" $("#accessoryFileTd").append(str);fileNum++;   }              <pre name="code" class="html">           // 删除附件上传控件   function deleteFile(num){$("#fileDiv"+num).html("");   }

 function deleteFile(file,id,num){  mini.confirm("是否确认删除服务器上的文件?", "确定",                        function (action) {                            if (action == "ok") {                                        $.post(                                            bootPATH+"/ajax3/uploadFile_deleteFile.action",                                           {"appAttachmentId":id},                                           function (data, textStatus){                                                                                                   if (data.result=="success")                                                   {                                                    $("#accessoryDiv"+num).html("");                                                    mini.alert("删除成功!");                                                   }                                                   else                                                   {                                                       mini.alert("操作失败!");                                                       return;                                                   }                                           }, "json");                                                    }                        }                     );  }
这是下载附件的JS ,其中appAttachmentId为附件路径
function exportSingle(appAttachmentId){             var url =   bootPATH+"/inner/uploadFile_downLoadFile.action?appAttachmentId="+appAttachmentId;   $("#actionForm").attr("action",url).submit();        }

上面这段代码也可以替换成下面这段:

<!-- 循环出已经上传的附件 -->  <a href='<%=path%>/inner/uploadFile_downLoadFile.action?appAttachmentId=<s:property value="#file.FILE_URL"/>' >         <s:property value='#file.FILE_NAME'/>  </a>  


然后是JAVA代码:

要想将附件上传到服务器,首先得建立一个存放附件的文件夹:

public final static String FILE_PATH = "Upload";  

然后给调用的方法传两个参数:文件名称和文件路径。

private void uploadingFileInnerSignInfo(Map map) throws Exception {String personId = map.get("personId").toString();String pactId = map.get("pactId").toString(); if(""!=map.get("accessoryFileFileName") && null!=map.get("accessoryFileFileName") && ""!=map.get("accessoryFile") && null!=map.get("accessoryFile")){String accessoryFileFileName = map.get("accessoryFileFileName").toString(); String accessoryFile = map.get("accessoryFile").toString();String[] files =  accessoryFile.split(",");        String[] fileNames = accessoryFileFileName.split(",");         for (int i = 0; i < files.length; i++)        {        FileParam param = new FileParam();         String fileUrl = CommonConstant.FILE_PATH + "/" + fileNames[i] + DateTool.getCurrrentDate2();    param.setPactId(pactId);    param.setFileName(fileNames[i]);                 param.setCreatedBy(personId);                param.setLastUpdateBy(personId);                param.setCreationDate(DateTool.getCurrrentDate1());                param.setLastUpdatedDate(DateTool.getCurrrentDate1());                uploadingFile(files[i], CommonConstant.FILE_PATH, fileNames[i], param);        }}  }
   /**     * 上传文件方法     * @return     */    public boolean uploadingFile(String files, String folderName,            String paramFileName, FileParam fileParam) throws Exception    {        if (files == null || paramFileName == null)        {            return false;        }        String currentDateStr = DateTool.getCurrrentDate2();        String name = FileUtil.getFileName(paramFileName) + "_"                + currentDateStr + "."                + FileUtil.getExtentionName(paramFileName);        FileOutputStream fos = null;        FileInputStream fis = null;        try        {            String folderPath = this.getServerFilePath(folderName);            File folderFile = new File(folderPath);            if (!folderFile.exists())            {                folderFile.mkdir();            }                        fis = new FileInputStream(files);            fos = new FileOutputStream(folderPath + "\\" + name);            byte[] buffer = new byte[102400];            int len = 0;            while ((len = fis.read(buffer)) > 0)            {                fos.write(buffer, 0, len);            }             fileParam.setFileUrl(folderName + "/" + name);            String sql = "INSERT INTO  pact_baseinfo_inner_signfile (pact_id,file_name,file_url,creation_date,created_by,last_update_date,last_updated_by) " ;               sql += "values ('"+ fileParam.getPactId()+"','"+fileParam.getFileName()+"','"+fileParam.getFileUrl()+"',sysdate,'" +fileParam.getCreatedBy()+"',sysdate,'"+fileParam.getLastUpdateBy()+"')";                              pactBaseinfoInnerSignDao.executeSQL(sql);                    }        catch (Exception e)        {            //e.printStackTrace();            return false;        }        finally        {            close(fos, fis);        }                return true;    }        /**     * 关闭文件流等对象     *      * @param fos     * @param fis     */    private void close(FileOutputStream fos, FileInputStream fis)    {        if (fis != null)        {            try            {                fis.close();            }            catch (IOException e)            {                e.printStackTrace();            }        }        if (fos != null)        {            try            {                fos.flush();                fos.close();            }            catch (IOException e)            {                e.printStackTrace();            }        }    }        /**     * 得到上传文件的详细路径     * @return     */    public String getServerFilePath(String folderName)    {        String basePath = ServletActionContext.getRequest()                .getSession()                .getServletContext()                .getRealPath("");        return basePath + "\\" + folderName;    }

删除和下载的关键代码

public class UploadFileAction {private UploadFileService uploadFileService;private String fileName;private InputStream inputStream;private String appAttachmentId;private String realPath = ServletActionContext.getServletContext().getRealPath("/");private Map resultMap=new HashMap(); public String downLoadFile(){try{Map fp = uploadFileService.queryFileRecordInDB(appAttachmentId);                        //下载前先判断数据库中是否存在这个文件                        if(null != fp){fileName = (String) fp.get("FILE_NAME");String path = realPath + fp.get("FILE_URL");                                //路径传到前台时路径中的“\”会被认为是转义符,所以保存时保存的“/”,这是作为参数传到后台需要重新替换下。                                path = path.replaceAll("/", "\\\\");inputStream = new FileInputStream(path);} }catch (Exception e){e.printStackTrace();}return "downLoad";    //如果dir是绝对路径}public String deleteFile(){try{Map fp = uploadFileService.queryFileRecordInDB(appAttachmentId);                       <pre name="code" class="html">                        //下载前先判断数据库中是否存在这个文件
 if (null != fp){String path =(String) fp.get("FILE_URL");
 uploadFileService.deleteFileRecordInDB(path);
//路径传到前台时路径中的“\”会被认为是转义符,所以保存时保存的“/”,这是作为参数传到后台需要重新替换下。  
path = path.replaceAll("/", "\\\\");String folderPath = getServerFilePath(CommonConstant.FILE_PATH).replace(CommonConstant.FILE_PATH, "");path = folderPath +path;uploadFileService.deleteFileInServer(path); }resultMap.put("result", "success");}catch (Exception e){resultMap.put("result", "error");}return "success";}
}

上传前需要对附件大小做个校验,不要超过10M。

@Override    public  boolean isOverSize(File file, int size)    {        if (file == null || !file.exists())        {            return false;        }        FileInputStream fis = null;        try        {            double fileSize = file.length()/1000000.0;                        if (fileSize <= size)            {                return false;            }            else            {                return true;            }                    }        catch (Exception e)        {            e.printStackTrace();            return false;        }        finally        {            if (fis != null)            {                try                {                    fis.close();                }                catch (IOException e)                {                    e.printStackTrace();                }            }        }            }


Struts2上传文件的默认大小限制是2M(2097152字节),如果想上传大于2M的文件,有两种修改方法:

 

1.  通过struts.properties文件中的struts.multipart.maxSize修改,如struts.multipart.maxSize=2048 表示一次上传文件的总大小不能超过2K字节。

 

2. 在struts.xml中,添加<constant name="struts.multipart.maxSize" value="2048"/>

 

我用的是第一中方法~~


struts.enable.DynamicMethodInvocation=truestruts.i18n.encoding=UTF-8struts.devMode=truestruts.custom.i18n.resources=globalMessagesstruts.multipart.saveDir=/docFiles#unit/B  set 2Gstruts.multipart.maxSize=2000000000struts.ognl.allowStaticMethodAccess=true






0 0
原创粉丝点击