Struts2文件上传与下载

本文介绍了一个用于发票上传、下载及删除的功能模块实现细节。通过Struts2框架完成文件的前后端交互,支持多种文件类型,并确保文件的安全存储与正确读取。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public class UploadAction extends BaseAction {

  private static final long serialVersionUID = -5692107751492990406L;

  private String title;

  private File upload;

  private String uploadContentType;

  private String uploadFileName;

  private String savePath;

  private String attachmentSubfix;

  private String attachmentName;

  private ErBusiness erBusiness;

  private ErBusinessManager erBusinessManager;

  public String editInvoice() {

    return SUCCESS;
  }

  public String uploadInvoice() throws IOException {

    String fileName = erBusiness.getBatchId()
        + getUploadFileName().substring(getUploadFileName().lastIndexOf("."));

    String fullPath = getFullPath(fileName);
    File attachment = new File(fullPath);
    // attachment.deleteOnExit();

    FileOutputStream fos = new FileOutputStream(attachment);

    FileInputStream fis = new FileInputStream(getUpload());
    byte[] buffer = new byte[1024];
    int len = 0;
    while ((len = fis.read(buffer)) > 0) {
      fos.write(buffer, 0, len);
    }

    fos.close();
    fis.close();

    erBusiness = erBusinessManager.getById(erBusiness.getId());
    erBusiness.setInvoiceURL(fileName);
    erBusiness.setInvoiceAlias(getTitle());
    erBusiness = erBusinessManager.save(erBusiness);

    freshFlag = 1;
    return SUCCESS;
  }

  public String downLoadInvoice() {

    return SUCCESS;
  }

  public String deleteInvoice() {
    erBusiness = erBusinessManager.getById(erBusiness.getId());

    String fileName = erBusiness.getInvoiceURL();
    File attachment = new File(getFullPath(fileName));
    attachment.delete();

    erBusiness.setInvoiceURL(null);
    erBusiness.setInvoiceAlias(null);
    erBusiness = erBusinessManager.save(erBusiness);
    return SUCCESS;
  }

  public InputStream getAttachmentInputStream() throws FileNotFoundException,
      UnsupportedEncodingException {
    erBusiness = erBusinessManager.getById(erBusiness.getId());

    String fileName = erBusiness.getInvoiceURL();

    attachmentName = erBusiness.getInvoiceAlias();

    attachmentName = new String(attachmentName.getBytes("GBK"), "ISO8859-1");

    attachmentSubfix = getSubfix(fileName);

    InputStream is = new FileInputStream(getFullPath(fileName));

    return is;
  }

  private String getSubfix(String fileName) {
    return fileName.lastIndexOf('.') >= 0 ? fileName.substring(fileName
        .lastIndexOf('.') + 1) : "";
  }

  private String getFullPath(String fileName) {
    if (ServletActionContext.getServletContext() != null)
      return ServletActionContext.getServletContext()
          .getRealPath(getSavePath())
          + "/" + fileName;
    String clzPath = UploadAction.class.getResource("").getPath();
    return clzPath.substring(0, clzPath.toUpperCase().lastIndexOf("/WEB-INF"))
        + getSavePath() + "/" + fileName;
  }

 

  /*get, set 方法省略*/

 

}

 

-------------------------------------------------------

<!-- upload file -->
  <action name="editInvoice"
   class="UploadAction"
   method="editInvoice">
   <result>/WEB-INF/reimbursement/uploadInvoice.jsp</result>
  </action>
  
  <action name="uploadInvoice"
   class="UploadAction"
   method="uploadInvoice">
   <interceptor-ref name="staticParams"/>
   <interceptor-ref name="fileUpload">
    <param name="allowedTypes">
    image/bmp,image/png,image/gif,image/jpeg,image/pjpeg,application/pdf,application/octet-stream,application/x-zip-compressed
    </param>
    <param name="maximumSize">2097152</param>
   </interceptor-ref>
   <interceptor-ref name="myDefaultStack"/>
   <param name="savePath">/WEB-INF/reimbursement/upload</param>
   <result name="input">/WEB-INF/reimbursement/uploadInvoice.jsp</result>
   <result>/WEB-INF/reimbursement/uploadInvoice.jsp</result>
  </action>
  
  <action name="downLoadInvoice"
   class="UploadAction"
   method="downLoadInvoice">
   <interceptor-ref name="staticParams"/>
   <interceptor-ref name="myDefaultStack"/>
   <param name="savePath">/WEB-INF/reimbursement/upload</param>
   <result name="success" type="stream">
    <param name="inputName">attachmentInputStream</param>
    <param name="contentType">
     application/${attachmentSubfix}; charset=utf-8
    </param>
    <param name="contentDisposition">
     attachment;filename="${attachmentName}"
    </param>
    <param name="BufferSize">8192</param>
   </result>
  </action>
  
  <action name="deleteInvoice"
   class="UploadAction"
   method="deleteInvoice">
   <result>/WEB-INF/reimbursement/erBusinessEdit.jsp</result>
  </action>


------------------------------

function deleteAttachment(erBusinessId){
  if(confirm("Are you sure to delete?")){
   $.post(
    "<s:url includeParams='none' action='deleteInvoice'></s:url>",
    {"erBusiness.id":erBusinessId},
    function(data, textStatus){
     if(textStatus=="success"){
      document.getElementById("div_attachment").style.display="none";
     }
    }
   );
  }
 }
function showAttachment(fileName){
 document.getElementById("div_attachment").style.display="block";
 fileName = fileName ? fileName : "Invoice Attachment";
 $("#a_attachment").text(fileName);
}

 

 

 

<div id="div_attachment" style="float:left;display:<s:if test="erBusiness.invoiceURL!=null">block</s:if><s:else>none</s:else>">
        <a id="a_attachment" href="<s:url action='downLoadInvoice'><s:param name='erBusiness.id' value='erBusiness.id'/></s:url>"><s:property value="erBusiness.invoiceAlias"/></a>
        <a href="javascript:;" onclick="deleteAttachment(<s:property value='erBusiness.id' />)" style="font-family:Wingdings 2; font-size:20px;color:red;text-decoration:none" title="delete">O</a>
     </div> 

 

<input id="uploadBtn" type="button" class="btn"
  onMouseOver="this.className='btn_on'"
  onMouseOut="this.className='btn'" value="Upload Invoice"
  onclick="showWin('<s:url action='editInvoice.action'><s:param name='erBusiness.batchId' value='erBusiness.batchId'/><s:param name='erBusiness.id' value='erBusiness.id'/></s:url>',500,150)"/>

--------------------------------------

 

<script type="text/javascript">
<!--
 <s:if test="freshFlag==1">
  opener.showAttachment('<s:property value="erBusiness.invoiceAlias"/>');
  window.close();
 </s:if>
 
 function setFileTitle(file){
 
  file = file.replaceAll('////','/');
  document.getElementById('file_title').value=file.substring(file.lastIndexOf('/')+1);
 }
 
//-->
</script>

 

 

<s:form action="uploadInvoice.action" method="post" onsubmit="disableAllButtons();" enctype="multipart/form-data">
 <s:hidden name="erBusiness.id"/>
 <s:hidden name="erBusiness.batchId"/>
 
  
 <table align="center" class="list">
   <tbody>
    <tr>
     <td valign="top" class="list_td per4_1">
     <div class="label">File Title<font
      class="font_star">*</font></div>
     </td>
     <td class="list_td per4_2" colspan="3">
     <div class="label"><s:textfield id="file_title" name="title" cssStyle="width:100%"></s:textfield></div>
     </td>
    </tr>
    
    <tr>
     <td valign="top" class="list_td per4_1">
     <div class="label">Upload File<font
      class="font_star">*</font></div>
     </td>
     <td class="list_td per4_2" colspan="3">
     <div class="label">
     <s:file name="upload" cssStyle="width:100%"  onchange="setFileTitle(this.value)"></s:file>
     </div>
     </td>
    </tr>
    
    <tr>
     <td width="25%"></td>
     <td width="25%"></td>
     <td width="25%"></td>
     <td width="25%"></td>
    </tr>

   </tbody>
  </table>
   <div id="btn"><input type="submit" class="btn"
  value="Upload" /> <input type="button"
  class="btn" value="<s:text name='system.button.close' />"
  onclick="window.close()" /></div>
</s:form>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值