简体   繁体   English

从python request.post在struts2中上传文件

[英]Upload file in struts2 from python requests.post

I have a jsp to upload a file in struts2 and works pretty well. 我有一个jsp可以在struts2中上传文件,效果很好。 But now I need upload a file from a external application ie python. 但是现在我需要从外部应用程序(例如python)上传文件。

I tried this but I receive a error message. 我尝试了此操作,但收到错误消息。

UploadFileAction.java 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 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 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) Struts.xml(部分)

<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 现在,当我尝试使用此脚本python上传文件时

Upload.py 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. 我认为问题可能是表单ID或名称以及会话ID,但我不知道如何在request.post中建立。

Perhaps I am completely wrong, and I would need a webservice programmed in struts. 也许我是完全错误的,并且我需要使用struts编程的Web服务。

The problem was the python script itself. 问题出在python脚本本身。 I have a file input field in struts called "file". 我在struts中有一个文件输入字段,称为“文件”。 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". 由于某些原因,我仍然不知道为什么,struts与名为“ file”的文件输入文件不匹配该变量。 That is why the file object was always null. 这就是为什么文件对象始终为null的原因。

Because I only used Python to test my Java code, I really don't needed. 因为我只使用Python测试我的Java代码,所以我确实不需要。 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. 谢谢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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