本文实例为大家分享了 Java 实现文件上传的具体代码 , 具体内容如下
1 、 Java 代码:
pacote com.github.reston.servlet; importar java.io.file; importar java.io.fileOutputStream; importar java.io.ioException; importar java.io.printwriter; importar java.util.iterator; importar java.util.list; importar javax.servlet.servletconfig; importar javax.servlet.servletexception; importar javax.servlet.annotation.webServlet; importar javax.servlet.http.httpSertlet; import javax.servlet.http.httlestlestlest; javax.servlet.http.httpServletResponse; importar org.apache.commons.fileupload.fileitem; importar org.apache.commons.fileupload.fileitemfactory; importar org.apache.commons.fileupload.disk.diskfileitemfactory; importlet.apache.commons.fileUloDisk.Disk.DiskFileItemFactory; importlet.apache.commons.fileUloDisk.Sisk.SiskFileItemFactory; org.apache.commons.io.ioutils; @WebServlet ("/ajaxupload") classe pública Ajaxupload estende httpServlet {@Override public void init (servletConfig config) lança servletexception {// togo-gerated method stub.init (config); } @Override Protected Void Service (solicitação httpServletRequest, httpServletResponse resposta) lança servletexception, ioexception {Response.setContentType ("text/html"); request.setcharacterencoding ("UTF-8"); boolean ismultipart = servletfileUpload.ismultipartContent (solicitação); String basalepath = getServletContext (). GetRealPath ("/upload"); Arquivo baseado em arquivo = novo arquivo (base); String filename = ""; long start = 0; if (! Basedirectory.isDirectory ()) baseado no retenção.mkdirs (); if (ismultipart) {try {FileItemFactory Factory = new DiskFileItemFactory (); ServletfileUpload upload = new ServletFileUpload (fábrica); @Suppresswarnings ("desmarcado") Lista <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 ()); }} para (item de fileItem: fileItems) {if (item.isformfield ()) continue; arquivo de arquivo = item.getfieldName (); if (mkdir (baseepath)) {arquivo fileOnserver = createfile (base, nome do arquivo); 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 (Exceção e) {}}} arquivo privado createfile (caminho da string, nome da string) lança IoException {arquivo tmp = new File (caminho, nome); if (! tmp.exists ()) {tmp.createnewfile (); } retornar tmp; } private boolean mkdir (caminho da string) {resultado booleano = true; Arquivo tmp = novo arquivo (caminho); if (! tmp.isdirectory ()) {resultado = tmp.mkdirs (); } resultado de retorno; }}2 Java 代码 ::
var ajaxUpload = function (e) { / ** * e URL Data Data Success Erro * / var xmlHttPrequest; if (window.xmlHttPrequest) {xmlhttPrequest = new XmlHttPrequest (); if (xmlHttPrequest.Overridemimetype) {xmlHttPrequest.Overridemimetype ("text/xml"); }} else if (window.activexObject) {var ativename = ["msxml2.xmlhttp", "microsoft.xmlhttp"]; for (var i = 0; i <ativeName.length; i ++) {try {xmlHttPrequest = new ActiveXObject (ActiveName [i]); quebrar; } catch (e) {return; }}} if (xmlHttPrequest == indefinido || xmlHttPrequest == null) {alert ("xmlHttPrequest 对象创建失败!!"); retornar; } else {this.xmlhttp = xmlhttPrequest; } var arquivo = document.getElementById (e.id); if (this.xmlhttp! = indefinido && this.xmlhttp! = null) {e.method = e.method.TOUPPERCASE (); if (e.method! = "get" && e.method! = "post") {alert ("http 的请求方法必须为 obtenha 或 post !!!"); retornar; } if (e.url == null || e.url == indefinido) {e.alert ("http 的请求地址必须设置!"); retornar; }} this.xmlhttp.onReadyStatechange = function () {if (this.readyState == 4) {if (this.status == 200) {var RespoteText = this.ResponseText; var respostaxml = this.reponsexml; if (e.success == indefinido || e.success == null) {alert ("没有设置处理数据正确返回的方法"); alerta ("返回的数据 ::" + RespoteText); } else {E.success (RespoteText, Responsexml); }} else {if (e.error == indefinido || eerror == null) {alert ("没有设置处理数据返回失败的处理方法!"); alerta ("http 的响应码:" + this.status + ", 响应码的文本信息:" + this.statustext); } else {e.error (this.status, this.statustext); }}}} // var formhtm = "<form = 'output' ENCTYPE = 'Multipart/form-data'> </morm>"; var filename = getFilename (e.id); this.xmlhttp.open (e.method, e.url, true); var dados = new FormData (document.getElementById ("output")); data.append ("nome", nome do arquivo); data.append ("start", e.data.start); data.append (nome do arquivo, document.getElementById (e.id) .Files [0] .slice (e.data.start, getfilesize (e.id))); this.xmlHttp.send (data);} função 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);} função getFilesize (id) {retornar 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> <body> <bodyscript "typen) value = "上传"/> <pan> 请选择要上传的文件 (小于 1g) </span> <input type = "button" value = "上传" onclick = "test ();"/> <form = "output" Enctype = "Multipart/form-data"> </morm> <script> function ") "/PCC/Reston/Ajaxupload", Método: "Post", Data: {Iniciar: 0}, Sucesso: function (e) {var L = json.parse (e) .Length; }, erro: função (e) {console.log (e); } </script> </body> </html>以上就是本文的全部内容 , 希望对大家学习 java 程序设计有所帮助。