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

时间:2016-08-29 13:12:30

标签: ajax file-upload struts2

我在服务器端使用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(&#34; POST&#34;,&#34;&#34;,true);     xml.setRequestHeader(&#34; Content-Type&#34;,&#34; false&#34;);

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

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

}

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

它是在服务器端类中,我试图通过使用request.getParameter(upload)来检索文件,但它给出了null。

2 个答案:

答案 0 :(得分:1)

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;

}

答案 1 :(得分:0)

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

你的Action课程怎么样?您是否使用getter / setter定义了名为上传File字段?

另请注意,您的浏览器支持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
}

我没有测试过这段代码,所以如果某些内容不起作用,请更改或添加评论。