1

i've wrote a code for uploading file from jsp to mysql database using jquery-ajax on selecting a file from file browser. on selecting a file the JavaScript passes the file and id as parameter to action class, but i'm getting null value for the file in action class.

can anyone please tell me how to solve this problem.

index.jsp

<%@taglib uri="/struts-tags" prefix="s"%>
<html>
<head>
<script src="js/jquery-1.7.2.min.js"></script>
<script src="js/jquery-ui-1.8.21.custom.min.js"></script>
<script>
    function filebrowse(toolid){
        document.getElementById("toolidforimg").value=toolid;
        $("#filetochange").trigger('click');
        return false;
    }

    function changeFile(var3)
    {
       var param="filetochange="+(document.getElementById("filetochange").value)+"&toolidforimg="+document.getElementById("toolidforimg").value;
        var resultStringX = $.ajax({
        type: "POST",
        url:"getFileChange.action", 
        enctype: 'multipart/form-data',
        data: param,
        async: false
        }).responseText;
        resultStringX=$.trim(resultStringX);

     return false;  
    }
</script>
</head>
<body>
<s:hidden value="" name="toolidforimg" id="toolidforimg"/>
<a href="#" onclick="return filebrowse('1')" id="select_logo">Change File</a>
<input style="opacity:0;" type="file" onchange="changeFile(this.value)" id="filetochange" name="filetochange" >
</body>
</html>

struts.xml

<action name="getFileChange" class="com.MyactionClass" method="getFileChange">
     <result name="success">browseFiles.jsp</result>
</action>

MyactionClass.java

class MyactionClass
{
  File filetockhange;
  String toolidforimg;

  public File getFiletochange() {
        return filetochange;
    }

  public void setFiletochange(File filetochange) {
        this.filetochange = filetochange;
    }

   public String getToolidforimg() {
        return toolidforimg;
    }

   public void setToolidforimg(String toolidforimg) {
        this.toolidforimg = toolidforimg;
    }

   public String getFileChange()
   {
    HERE I AM GETTING filetochange VALUE AS NULL

    return SUCCESS;
   }
}

1 Answers1

0

Put an HTML Form element around the fields you want to send (File, Hidden, etc).

That should be enough.

Some hints:

  • always specify a DTD, or you will fall in the odd world of the Quirks Mode. In your case, the HTML5 DTD should fit because you can upload files through AJAX only with HTML5: change <html> with <!DOCTYPE html>
  • always use Struts2 Tags instead of HTML tags when possible, like <s:form>, <s:file> and <s:a>.
  • only the accessors (getters) should begin with get, not other methods and for sure not an Action name;
Andrea Ligios
  • 49,480
  • 26
  • 114
  • 243