简体   繁体   中英

Upload file in struts2 from python requests.post

I have a jsp to upload a file in struts2 and works pretty well. But now I need upload a file from a external application ie python.

I tried this but I receive a error message.

UploadFileAction.java

import java.io.File;
import java.io.IOException;
import javax.servlet.ServletContext;
import org.apache.struts2.util.ServletContextAware;
import com.appweb.FileUtil;
impoRt com.opensymphony.xwork2.ActionSupport;

public class UploadFileAction extends ActionSupport implements ServletContextAware{

private static final long serialVersionUID = -4748500436762141116L;

@Override
public String execute(){
    System.out.println("File Name is:"+getFileFileName());
    System.out.println("File ContentType is:"+getFileContentType());
    System.out.println("Files Directory is:"+filesPath);
    try {
        FileUtil.saveFile(getFile(), getFileFileName(), context.getRealPath("") + File.separator + filesPath);
    } catch (IOException e) {
        e.printStackTrace();
        return INPUT;
    }
    return SUCCESS;

}

private File file;
private String fileContentType;
private String fileFileName;
private String filesPath;
private ServletContext context;

public File getFile() {
    return file;
}

public void setFile(File file) {
    this.file = file;
}

public String getFileContentType() {
    return fileContentType;
}

public void setFileContentType(String fileContentType) {
    this.fileContentType = fileContentType;
}

public String getFileFileName() {
    return fileFileName;
}

public void setFileFileName(String fileFileName) {
    this.fileFileName = fileFileName;
}

public void setFilesPath(String filesPath) {
    this.filesPath = filesPath;
}

@Override
public void setServletContext(ServletContext ctx) {
    this.context=ctx;
}

}

FileUtil.java

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileUtil {

public static void saveFile(File file, String fileName, String filesDirectory) throws IOException{
    FileInputStream in = null;
    FileOutputStream out = null;

    File dir = new File (filesDirectory);
    if ( !dir.exists() )
       dir.mkdirs();

    String targetPath =  dir.getPath() + File.separator + fileName;
    System.out.println("source file path ::"+file.getAbsolutePath());
    System.out.println("saving file to ::" + targetPath);
    File destinationFile = new File ( targetPath);
    try {
        in = new FileInputStream( file );
        out = new FileOutputStream( destinationFile );
        int c;

        while ((c = in.read()) != -1) {
            out.write(c);
        }

    }finally {
        if (in != null) {
            in.close();
        }
        if (out != null) {
            out.close();
        }
    }

}
}

UploadFile.jsp

<%@ page language="java" contentType="text/html; charset=US-ASCII"
    pageEncoding="US-ASCII"%>
<%@ taglib uri="/struts-tags"  prefix="s"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Upload File Page</title>
</head>
<body>
<h3>Select File to Upload</h3>
<s:form action="UploadFile" method="post" enctype="multipart/form-data">
<s:file label="File" name="file"></s:file>
<s:submit value="Upload"></s:submit>
</s:form>
</body>
</html>

Struts.xml (part)

<action name="upload">
            <result>/UploadFile.jsp</result>
</action>
<action name="UploadFile" class="com.imagramint.appweb.UploadFileAction">
    <param name="filesPath">myfiles</param>
    <result name="success">/UploadFileSuccess.jsp</result>
    <result name="input">/UploadFile.jsp</result>

    <interceptor-ref name="defaultStack">
        <param name="fileUpload.maximumSize">10485760</param>
        <param name="fileUpload.allowedTypes">text/plain,image/jpeg</param>
    </interceptor-ref> 
</action>

Now when I tried to upload the file with this scripts python

Upload.py

import requests
r = requests.post('http://localhost:8080/Struts2Hibernate/UploadFile.action', files={'file': open('a.jpg', 'rb')})
print r.text

I received this error

HTTP Status 500 -

type Exception report

message

description The server encountered an internal error that prevented it from fulfilling this request.

exception

java.lang.NullPointerException
    com.imagramint.appweb.FileUtil.saveFile(FileUtil.java:19)
    com.imagramint.appweb.UploadFileAction.execute(UploadFileAction.java:24)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    java.lang.reflect.Method.invoke(Method.java:497)
    com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:450)
    com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:289)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:252)
    org.apache.struts2.interceptor.DeprecationInterceptor.intercept(DeprecationInterceptor.java:41)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:256)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:167)
    com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:265)
    org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68)
    com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:138)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:254)
    com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:254)
    com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:191)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:73)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:91)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:325)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:100)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:141)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:145)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:171)
    com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:139)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:193)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:189)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
    org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:54)
    org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:562)
    org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77)
    org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:99)

note The full stack trace of the root cause is available in the Apache Tomcat/7.0.62 logs.

I think the problem could be the form id or name and also the session id but I don't know how to establish in the requests.post.

Perhaps I am completely wrong, and I would need a webservice programmed in struts.

The problem was the python script itself. I have a file input field in struts called "file". So when I ran

files = {'file': open('perro.jpg', 'rb')}
r = requests.post('http://localhost:8080/Struts2Hibernate/UploadFile.action', files=files, data=datos,cookies=cookie)

it seems that variable "files" is a dictionary that contains a file called "file". For some reason, I still don't know why, struts doesn't match that variable with the file input file called "file". That is why the file object was always null.

Because I only used Python to test my Java code, I really don't needed. So I tried with Curl

curl -H "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" -F "file=@/home/a.JPG" localhost:8080/Struts2Hibernate/UploadFile.action

which it has a field called "file" and I finally could upload the file.

Thank you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM