java接收ajax上传文件_java-JSP AJAX文件上传

我试图上传一个文件,并使用ajax和jsp将文件的内容显示回浏览器.但是,它对我来说似乎不太好用.

显然,在JSP页面Upload.jsp中,当我尝试从请求中获取getContentType()时,request.getcontentType()== null.

有人对此有经验吗?非常感谢

形成

这是Javascript函数upload(ifile)

function upload(ifile){

if (window.XMLHttpRequest){

//IE7 + and other browsers

xmlhttp = new XMLHttpRequest();

}else{

//IE 6, 5

xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");

}

if(xmlhttp == null){

alert("File Uploading is not available because your browser does not support AJAX");

return;

}

//Function to process response form upload.jsp

xmlhttp.onreadystatechange = function(){

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

var response = xmlhttp.responseText;

alert(response);

}

}

xmlhttp.open("POST", "Upload.jsp?file="+ifile, true);

xmlhttp.send(null);

}

这是JSP页面Upload.jsp

response.setContentType("text/html");

response.setHeader("Cache-control", "no-cache");

String contentType = request.getContentType();

if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0)) {

DataInputStream in = new DataInputStream(request.getInputStream());

//get length of Content type data

int formDataLength = request.getContentLength();

byte dataBytes[] = new byte[formDataLength];

int byteRead = 0;

int totalBytesRead = 0;

//convert the uploaded file into byte code

while (totalBytesRead < formDataLength) {

byteRead = in.read(dataBytes, totalBytesRead,formDataLength);

totalBytesRead += byteRead;

}

//decode byte array using default charset

String file = new String(dataBytes);

//Using StringTokenizer to extract genes list

StringTokenizer st = new StringTokenizer(file, " ");

int numtoken = st.countTokens();

for(int i = 0; i < numtoken-1; i++){

st.nextToken();

}

String a = st.nextToken();

st = new StringTokenizer(a, " \n");

numtoken = st.countTokens();

String postlink = "";

st.nextToken();

st.nextToken();

for(int i = 1; i < numtoken-3; i++){

String temp = st.nextToken();

char[] c = temp.toCharArray();

temp = new String(c, 0, c.length-1);

if(!" ".equalsIgnoreCase(temp)){

postlink = postlink + temp + ",";

}

}

String temp = st.nextToken();

postlink = postlink + temp;

out.println(postlink);

out.flush();

out.close();

}else if (contentType == null){

out.println("Not a valid file");

out.flush();

}

%>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值