Uploading image using Struts

前端 未结 3 1464
梦如初夏
梦如初夏 2021-01-27 09:08

I just started practicing struts, so I\'m kinda new to this framework. So, what I\'m trying to do is upload an image using this JSP file :



        
相关标签:
3条回答
  • 2021-01-27 09:48

    You can start with simple file upload example then you can see where the uploaded file is stored. If you get the uploaded file name is set you can copy file. You can prevent null pointer exception before you start saving.

    if (myFileFileName != null)
      InsertImage.save(this);  
    

    You can also add required validator that will check the field value before your action is executed.

    0 讨论(0)
  • 2021-01-27 09:50

    Try to use <s:file name="Image"/> tag instead of plain <input/>

    0 讨论(0)
  • 2021-01-27 09:57
    1. Change your input name to begin with a lowercase character:

      <input type="file" name="image">
      
    2. Then in Action you need to prepend the File variable's name to the contentType and FileName Strings, as follows:

      private File image;
      private String imageContentType;
      private String imageFileName;
      
      /* GETTERS AND SETTERS FOR ALL OF THEM */
      

    You may also being interested in how to configure the maximum size for a single file (and for the entire request), allow only certain kind of files to be uploaded, or upload multiple files at once.

    EDIT

    You didn't post your struts.xml and web.xml configuration, but the line of the stacktrace

    at org.apache.struts2.dispatcher.FilterDispatcher.doFilter(FilterDispatcher.java:395)

    unveils that you are using the wrong Filter.

    Also the File Upload Interceptor seems to be configured to run twice... and this usually happens when configuring it the wrong way, like

    <!-- WRONG  -->
    <interceptor-ref name="fileUpload">
        <param name="maximumSize">2097152</param>
        <param name="allowedTypes">
            image/png,image/gif,image/jpeg,image/pjpeg
        </param>            
    </interceptor-ref>
    <interceptor-ref name="defaultStack" />
    

    instead of

    <!-- RIGHT  -->
    <interceptor-ref name="defaultStack">
        <param name="fileUpload.maximumSize">2097152</param>
        <param name="fileUpload.allowedTypes">
            image/png,image/gif,image/jpeg,image/pjpeg
        </param>            
    </interceptor-ref>
    

    Again, check carefully your configuration both in web.xml and struts.xml, it will work automatically.

    0 讨论(0)
提交回复
热议问题