使用Struts 2上传图片 [英] Uploading image using Struts 2

查看:42
本文介绍了使用Struts 2上传图片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要做的就是使用此JSP文件上传图像:

What I'm trying to do is upload an image using this JSP file :

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
 
<html>
  <head>
    <title>Upload User Image</title>
  </head>
 
  <body>
    <h2>Struts2 File Upload &amp; Save Example</h2>
 
    <s:actionerror />
    <s:form action="imageinsert.action" method="post" enctype="multipart/form-data">

      <td>Image : </td><td><input type="file" name="Image"></td> 
      <s:submit value="Upload" align="center" />
    </s:form>
  </body>
</html>

动作类如下:

public class InsertImageBean extends ActionSupport{
   
    private static final long serialVersionUID = 1L;
   
    private File Image;
    private String myFileContentType;
    private String myFileFileName;
   
    public String execute()
    {
        /* Copy file to a safe location */
     
        InsertImage.save(this);

        return SUCCESS;
    }
    public File getMyFile() {
        return Image;
    }
    public void setMyFile(File myFile) {
        this.Image = myFile;
    }
    public String getMyFileContentType() {
        return myFileContentType;
    }
    public void setMyFileContentType(String myFileContentType) {
        this.myFileContentType = myFileContentType;
    }
    public String getMyFileName() {
        return myFileFileName;
    }
    public void setMyFileName(String myFileFileName) {
        this.myFileFileName = myFileFileName;
    }
}

bean类如下:

public class InsertImage {

    public static int save(InsertImageBean iib) {
        try{
            String filepath = "D:/TEAMWORK/NaTelangana/WebContent/Images";
            File image = iib.getMyFile();
            String myfilename = iib.getMyFileName();
            System.out.println("Src File name: " + iib.getMyFileName());
            System.out.println("Dst File name: " + myfilename);
                     
            File destFile  = new File(filepath, myfilename); // Null pointer exception is thrown here
            FileUtils.copyFile(image, destFile);
            
            System.out.println(System.getProperty("user.dir") );
            
            if(image.renameTo(new File(filepath)))
                System.out.println("File is moved successful!");
            else
                System.out.println("Failed to move!");
        }catch(Exception e){
            e.printStackTrace();
        }
        return 0;
    }
}

问题是,在上述程序中,我在此行附近的上方程序中得到了 NullPointerException :

Problem is, in the above program I'm getting a NullPointerException in the program above near this line:

File destFile  = new File(filepath, myfilename);

问题是在Bean文件中没有接收到发送的输入.如何纠正此错误?

The problem is the input sent is not being received in the bean file. How do I rectify this error ?

这是我得到的错误:

java.lang.NullPointerException
    at java.io.File.<init>(File.java:317)
    at natelangana.com.InsertImage.save(InsertImage.java:23)
    at bean.com.InsertImageBean.execute(InsertImageBean.java:26)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:440)
    at com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:279)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:242)Src File name: null
Dst File name: null

    at com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:163)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
    at com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:249)
    at org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
    at com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:122)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
    at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
    at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
    at com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:148)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
    at org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:93)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
    at org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:306)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
    at com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:89)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
    at com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:128)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
    at org.apache.struts2.interceptor.ProfilingActivationInterceptor.intercept(ProfilingActivationInterceptor.java:104)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
    at org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:267)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
    at com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:126)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
    at com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:138)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
    at com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:148)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
    at org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
    at com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:128)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
    at com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:176)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
    at org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:306)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
    at org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:52)
    at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:468)
    at org.apache.struts2.dispatcher.FilterDispatcher.doFilter(FilterDispatcher.java:395)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:164)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:462)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:562)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:395)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:250)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:188)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:744)

推荐答案

  1. 更改输入名称以小写字母开头:

  1. Change your input name to begin with a lowercase character:

<input type="file" name="image">

  • 然后在操作中,您需要将File变量的名称添加到contentType和FileName字符串的前面,如下所示:

  • 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.

    编辑

    您没有发布struts.xml和web.xml配置,但是发布了stacktrace的行

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

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

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

    显示您使用的是错误的过滤器.

    文件上传拦截器"似乎也配置为运行两次...,这通常是在配置错误的方式时发生的,例如

    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" />
    

    代替

    <!-- 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>
    

    再次,仔细检查web.xml和struts.xml中的配置,它将自动运行.

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

    这篇关于使用Struts 2上传图片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆