Java实现文件上传的方法
程序员文章站
2024-03-12 11:04:08
本文实例为大家分享了java实现文件上传的具体代码,具体内容如下
1、java代码:
package com.github.reston.servlet;...
本文实例为大家分享了java实现文件上传的具体代码,具体内容如下
1、java代码:
package com.github.reston.servlet; import java.io.file; import java.io.fileoutputstream; import java.io.ioexception; import java.io.printwriter; import java.util.iterator; import java.util.list; import javax.servlet.servletconfig; import javax.servlet.servletexception; import javax.servlet.annotation.webservlet; import javax.servlet.http.httpservlet; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; import org.apache.commons.fileupload.fileitem; import org.apache.commons.fileupload.fileitemfactory; import org.apache.commons.fileupload.disk.diskfileitemfactory; import org.apache.commons.fileupload.servlet.servletfileupload; import org.apache.commons.io.ioutils; @webservlet("/ajaxupload") public class ajaxupload extends httpservlet{ @override public void init(servletconfig config) throws servletexception{ // todo auto-generated method stub super.init(config); } @override protected void service(httpservletrequest request,httpservletresponse response) throws servletexception,ioexception{ response.setcontenttype("text/html"); request.setcharacterencoding("utf-8"); boolean ismultipart=servletfileupload.ismultipartcontent(request); string basepath=getservletcontext().getrealpath("/upload"); file basedirectory=new file(basepath); string filename=""; long start=0; if(!basedirectory.isdirectory()) basedirectory.mkdirs(); if(ismultipart){ try{ fileitemfactory factory=new diskfileitemfactory(); servletfileupload upload=new servletfileupload(factory); @suppresswarnings("unchecked") list<fileitem> fileitems=upload.parserequest(request); for(fileitem i:fileitems){ if(i.isformfield()){ string name=i.getfieldname(); string value=i.getstring(); if(name.equals("start"))start=long.parselong(i.getstring()); } } for(fileitem item:fileitems){ if(item.isformfield()) continue; filename=item.getfieldname(); if(mkdir(basepath)){ file fileonserver=createfile(basepath,filename); if(fileonserver.length()==0){ fileoutputstream fos=new fileoutputstream(fileonserver,true); ioutils.copy(item.getinputstream(),fos); } if(start>0){ fileoutputstream fos=new fileoutputstream(fileonserver,true); ioutils.copy(item.getinputstream(),fos); } printwriter pw=response.getwriter(); pw.write("{\"length\":\""+fileonserver.length()+"\"}"); pw.flush(); } } }catch(exception e){ } } } private file createfile(string path,string name) throws ioexception{ file tmp=new file(path,name); if(!tmp.exists()){ tmp.createnewfile(); } return tmp; } private boolean mkdir(string path){ boolean result=true; file tmp=new file(path); if(!tmp.isdirectory()){ result=tmp.mkdirs(); } return result; } }
2、java代码:
var ajaxupload = function(e) { /** * e url method data success error */ var xmlhttprequest; if (window.xmlhttprequest) { xmlhttprequest = new xmlhttprequest(); if (xmlhttprequest.overridemimetype) { xmlhttprequest.overridemimetype("text/xml"); } } else if (window.activexobject) { var activename = [ "msxml2.xmlhttp", "microsoft.xmlhttp" ]; for (var i = 0; i < activename.length; i++) { try { xmlhttprequest = new activexobject(activename[i]); break; } catch (e) { return; } } } if (xmlhttprequest == undefined || xmlhttprequest == null) { alert("xmlhttprequest对象创建失败!!"); return; } else { this.xmlhttp = xmlhttprequest; } var file = document.getelementbyid(e.id); if (this.xmlhttp != undefined && this.xmlhttp != null) { e.method = e.method.touppercase(); if (e.method != "get" && e.method != "post") { alert("http的请求方法必须为get或post!!!"); return; } if (e.url == null || e.url == undefined) { e.alert("http的请求地址必须设置!"); return; } } this.xmlhttp.onreadystatechange = function() { if (this.readystate == 4) { if (this.status == 200) { var responsetext = this.responsetext; var responsexml = this.reponsexml; if (e.success == undefined || e.success == null) { alert("没有设置处理数据正确返回的方法"); alert("返回的数据:" + responsetext); } else { e.success(responsetext, responsexml); } } else { if (e.error == undefined || e.error == null) { alert("没有设置处理数据返回失败的处理方法!"); alert("http的响应码:" + this.status + ",响应码的文本信息:" + this.statustext); } else { e.error(this.status, this.statustext); } } } } // var formhtm="<form id='output' enctype='multipart/form-data' ></form>"; var filename = getfilename(e.id); this.xmlhttp.open(e.method, e.url, true); var data = new formdata(document.getelementbyid("output")); data.append("name", filename); data.append("start", e.data.start); data.append(filename, document.getelementbyid(e.id).files[0].slice(e.data.start, getfilesize(e.id))); this.xmlhttp.send(data); } function getfilename(id) { var path = document.getelementbyid(id).value var pos1 = path.lastindexof('/'); var pos2 = path.lastindexof('\\'); var pos = math.max(pos1, pos2); return path.substring(pos + 1); } function getfilesize(id) { return document.getelementbyid(id).files[0].size; }
3、html代码:
<!doctype html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <script type="text/javascript" src="test.js"></script> </head> <body> <input type="file" name="upload" id="upload" value="上传"/><span>请选择要上传的文件(小于1g)</span> <input type="button" value="上传" onclick="test();"/> <form id="output" enctype="multipart/form-data" ></form> <script> function test(){ ajaxupload({ id : "upload", url : "/pcc/reston/ajaxupload", method : "post", data : {start:0}, success : function(e) { var l=json.parse(e).length; ajaxupload({ id : "upload", url : "/pcc/reston/ajaxupload", method : "post", data : {start:l}, success : function(e) { }, error : function(e) { console.log(e); } }); }, error : function(e) { console.log(e); } }); } </script> </body> </html>
以上就是本文的全部内容,希望对大家学习java程序设计有所帮助。