# Struts2上傳檔案和下載檔案功能實作 [參考網站](https://www.itread01.com/content/1548975252.html) ```htmlmixed=\ <s:form id="mailMaintainAddform" method="post" enctype="multipart/form-data"> <tr> <th></font>附件上傳</th> <td colspan=3> <span style="font-weight: bold;">附加檔案1:</span> <s:file label="匯入" name="uploadFile" /> <br> <span style="font-weight: bold;">附加檔案2:</span> <s:file label="匯入" name="uploadFile" /> <br> <span style="font-weight: bold;">附加檔案3:</span> <s:file label="匯入" name="uploadFile" /> <br> </td> </tr> </s:form> ``` ```java=\ private File [] uploadFile; private String [] uploadFileFileName; private String [] uploadFileContentType; ...getter setter if(uploadFile!=null){ List<MailAttachment> attachmentlist = new ArrayList<MailAttachment>(); for(int i=0;i<uploadFile.length;i++){ //1.輸出上傳的型別 logger.info("上傳的檔案:"+this.getUploadFile()[i]); logger.info("上傳檔案的名稱用File取得:"+this.getUploadFile()[i].getName()); logger.info("直接用屬性取得名稱:"+this.getUploadFileFileName()[i]); logger.info("檔案上傳的型別:"+this.getUploadFileContentType()[i]); String[] tempArray = this.getUploadFileFileName()[i].split("\\."); String fileType = ""; if(tempArray.length > 0) { logger.info("tempArray[tempArray.length-1]:"+tempArray[tempArray.length-1]); fileType = tempArray[tempArray.length-1]; } logger.info("FileType:"+fileType); logger.info("開始進行加密成BASE64"); BASE64Encoder en = new BASE64Encoder(); byte[] bytes = loadFile(this.getUploadFile()[i]); String encodedString = en.encodeBuffer(bytes); logger.info("加密BASE64完成"); logger.info("encodedString:"+encodedString); MailAttachment att = new MailAttachment(); att.setFileBase64(encodedString); att.setFileName(StringUtils.substring(this.getUploadFileFileName()[i],0,300)); att.setFilePath(""); att.setFileType(fileType); att.setMailAttSeq(mailDao.getSeqAttachmentNo()); att.setMailSeq(seq); att.setCreateDate(DateUtils.getSysDate()); att.setCreateTime(new Date()); att.setCreateUserId(userId); attachmentlist.add(att); } logger.info("attachmentlist:"+attachmentlist); mailDao.saveMailAttachment(mailBean, attachmentlist); } private static byte[] loadFile(File file) throws IOException { InputStream is = new FileInputStream(file); long length = file.length(); if (length > Integer.MAX_VALUE) { // File is too large } byte[] bytes = new byte[(int)length]; int offset = 0; int numRead = 0; while (offset < bytes.length && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) { offset += numRead; } if (offset < bytes.length) { throw new IOException("Could not completely read file "+file.getName()); } is.close(); return bytes; } ``` ###### tags: `javascript` `Java`