从javascript变量读取文件路径并将其发送到表单操作?

时间:2014-04-26 22:04:57

标签: java html jsp servlets web-applications

代码:

<script type="text/javascript">
     function showFileName() {
              var filename = document.getElementById("uploadFile");
      }
</script>

OR

<script type="text/javascript">

      var filename = document.getElementById("uploadFile");

</script>

OR

var filename="uploadedfilename";

<form name="AttachmentsForm" method="post"  action="<%=Constants.WEB_APP_NAME%><%=Constants.SERVLET_NAME%>?para=ajaxRefTabUpload&action=add&uploadfilename="+filename+"" ENCTYPE="multipart/form-data">
    <table class="innerBorderTable" width="100%">
       <tr>                                
    <td>Attach New File:</td>
    <td>
      <INPUT TYPE="FILE" NAME="uploadFile" width="120"> 
      <input type="submit" class="button" value="Add Attachment">
    </td>      
       </tr>
    </table>
</form>

我尝试了3种不同的方法来传递+filename+我在动作参数

中获得null uploadfilename

请告知

2 个答案:

答案 0 :(得分:0)

尝试类似:

function showFileName() { 
    document.forms[0].action ="<%=Constants.WEB_APP_NAME%>... //Here goes the expression you want to set the action to
}

答案 1 :(得分:0)

  

强烈建议不要在JSP中使用scriptlet(<% %>),使用JSTL<c:tags)或表达式语言(${}

在jsp download jstl.x.x.jar文件中使用JSTL并将其添加到构建路径中。

然后,添加此

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

在jsp的顶部。


解决您拥有的表单操作网址:

<%=Constants.WEB_APP_NAME%><%=Constants.SERVLET_NAME%>

不需要任何常量,而是使用<c:url标记来解析网址,如:

<c:url value="/yourServletUrl" var="postUrl"/>
<form action="${postUrl}"  method="post" ...
  

我在action参数

中使用uploadfilename获取null

因为你在html(&uploadfilename="+filename+")中访问javascript变量,而是喜欢:

<强> JSP

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
  <title>your title</title>
</head>
<body>

<c:url value="/yourServletUrl" var="postUrl"/>
<form id="AttachmentsForm"
      method="post"
      onSubmit="showFileName()"
      action="${postUrl}para=ajaxRefTabUpload&action=add"
      enctype="multipart/form-data">

    <table class="innerBorderTable" width="100%">
       <tr>                                
         <td>Attach New File:</td>
         <td>
           <input type="file" name="uploadFile" width="120"> 
           <input type="submit" class="button" value="Add Attachment">
         </td>      
       </tr>
    </table>
</form>
<script type="text/javascript">
     function showFileName(e) {

         if (e.preventDefault)
             e.preventDefault();

         var filename = document.getElementById("uploadFile");
         alert('fileName: '+filename);

         //here, attach filename to from action and continue your form submition by AJAX

          // You must return false to prevent the default form behavior
          return false;
        }
      }

</script>
</body>
</html>