xiayumao
xiayumao

Reputation: 1

File uploading can not work using Struts 2 and Uploadify

My JSP page like this:

$(function() {  
    $("#file_upload").uploadify({  
        'height': 27,
        'width': 80,
        'buttonText':'浏览',
        'swf':'<%=basePath%>admin/tupian/js/uploadify.swf',
        'uploader': '<%=basePath%>Imguploadoper.img',
        'auto' : false,
        'fileTypeExts' : '*.jpg'
        });
});

Here is my java code:

ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("UTF-8");
try {
    //this line returns null
    List items = upload.parseRequest(request);
    Iterator itr = items.iterator();
    while (itr.hasNext()) {
        ......
    }
} catch (FileUploadException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
out.flush();
out.close();

upload.parseRequest(request) returns null. I really don't know the reason.

Upvotes: -1

Views: 1109

Answers (1)

Roman C
Roman C

Reputation: 1

This is a common mistake when uploading in Struts2. You shouldn't parse the request in the action. I believe that you've written the java code in the action. So, Struts2 handles multipart request via the MultipartRequestWrapper, which is using the configuration constant

struts.multipart.parser=jakarta

that corresponds to the multipart request adapter JakartaMultiPartRequest, used to parse the request and put files to the location defined by this constant struts.multipart.saveDir, if this constant isn't set then javax.servlet.context.tempdir used by default.

You can get MultipartRequestWrapper using ServletActionContext, see How do we upload files.

Then fileUpload interceptor, which is a part of the defaultStack, using the maltipart request get all accepted files, accepted file names and accepted content types and put them to the action context.

Then params interceptor, which is a part of the defaultStack, using that action context params, put them to the action properties.

When multipart request wrapped, which is done by the Dispatcher, and parsed when wrapper is instantiated, you can check files in the saveDir, if uploading finished without errors.

To perform file uploading make sure you submit the multipart request, i.e the form enctype attribute is "multipart/form-data" and interceptors are applied to the action explicitly referencing them or implicitly using defaultStack of interceptors. In the action create properties with getters/setters for file names, content types, and files. If your uploads are succeeded then check your files in the action properties.

To learn more you can exercise these examples:

Upvotes: 0

Related Questions