如何在 java 服务器端使用 ajax 检索上传的文件?

How to retrieve uploaded file using ajax on java server side?

我在服务器端使用 struts2 框架。我正在使用

上传文件

服务器端:

<s:file name="fTU" id="fTU"/>

<input type="submit" value ="ok" onclick="upload()">

客户端:

function upload(){

var file = document.getElementById("fTU");

try {
    this.xml = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
    try {
        this.xml = new ActiveXObject("Microsoft.XMLHTTP");
    } catch (err) {
        this.xml = null;
    }
}
if(!this.xml && typeof XMLHttpRequest != "undefined")
    this.xml = new XMLHttpRequest();
if (!this.xml){
    this.failed = true; 
}

var formData = new FormData();
/* Add the file */ 
formData.append("upload", file.files[0]);

xml.open("POST", "", 真); xml.setRequestHeader("Content-Type", "false");

xml.send(formData);  /* Send to server */

xml.onreadystatechange = function () {
    if (xml.readyState == 4 && xml.status == 200) {
        alert(xml.statusText);
    }
}

}

如何在struts2服务器端获取上传的文件对象?

它正在服务器端 class 并且我正在尝试使用 request.getParameter(上传)检索文件,但它给出了 null。

我认为您错过了在 xml.open() 方法中添加操作 Link。查看 MDN 以查看一些示例。

你的 Action-class 长什么样?您是否使用 getter/setters?

定义了名为 uploadFile 字段

另请检查您的浏览器是否支持 FormData 元素,请参阅 question

我还建议您使用像 jQuery 这样的库来简化 Javascript 代码。

动作

public class FileUpload extends ActionSupport {
   File myFile;

   public String execute() {
       //do some preparations for the upload
       return SUCCESS;
   }

   public String upload() {
       //only here the myFile is filled with data
       return SUCCESS;
   }

   public void setMyFile(File myFile) {
       this.myFile = myFile;
   }

   public File getMyFile() {
       return myFile;
   }
}

struts.xml

<!-- init method to show the form -->
<action name="fileForm" class="...FileUpload">
    <result name="success">fileupload.jsp</result>
</action>

<!-- upload method to upload the file -->
<action name="fileUpload" class="...FileUpload" method="upload">
    <result name="success">fileupload.jsp</result>
</action>

JSP

<s:form enctype="multipart/form-data" method="post" name="fileinfo" action="fileUpload">
    <s:file name="myFile"/>
</s:form>

<input type="submit" onClick="upload()" value="OK"> 

Javascript(取自上面的 MDN 示例)

function upload() {
   var fd = new FormData(document.querySelector("form"));
   $.ajax({
       url : "fileUpload", //this is the actionName
       type: "POST",
       data: fd,
       processData: false,
       contentType: false
   });

   return false; //to stop submitting the form
}

我没有测试过这段代码,所以如果有什么不对,请更改它或添加评论。

function upload(form){
   var fd = new FormData(form);
   $.ajax({
       url : "<url-value>", //this is the actionName
       type: "POST",
       data: fd,
       processData: false,
       contentType: false,
       success: function(data){
        },
        error: function(xhr, status, error){
            var err = eval("(" + xhr.responseText + ")");
            alert(err.Message);
        }
    });
    return false;
}