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

I am using struts2 framework on server side. I am uploading a file using

server side :

client side :

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", "", true);

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

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

xml.onreadystatechange = function () {

if (xml.readyState == 4 && xml.status == 200) {

alert(xml.statusText);

}

}

}

How to fetch the uploaded file object on struts2 server side?

It is going in server side class and I am trying to retrieve file by using request.getParameter(upload) but it is giving null.

解决方案

I think you missed to add the Action Link in the xml.open() method. Take a look at the MDN to see some examples.

How does your Action-class look like? Have you defined a File field named upload with getter/setters?

Please also check, that your browser supports the FormData element, see question.

I also would suggest you to use a library like jQuery to simplify the Javascript code.

Action

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

fileupload.jsp

fileupload.jsp

JSP

Javascript (taken from the MDN example above)

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

}

I have not tested this code, so please change it or add comments if something doesn't work.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值