本文实例为大家分享了 java 实现文件上传的具体代码 具体内容如下 具体内容如下
1 、 java 代码 :
paquete 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.httttttttttpservlettpslettpslettpsettpsingtpservlettpSeNTPSEltpSeRVELTPSEHTPSEHTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT importar org.apache.commons.fileupload.fileitem; import org.apache.commons.fileupload.fileitemFactory; import org.apache.commons.fileupload.disk.diskfileitemFactory; import org.apache.commons.fileplet.servlet.servletfilepletfilepletfilepletfilePlet; org.apache.commons.io.ioutils; @WebServlet ("/AJAXUPLOAD") clase pública Ajaxupload extiende httpservlet {@Override public void init (servletConfig config) lanza ServletException {// TODO Autom general de método Generado súper.init (config); } @Override Servicio void protegido (solicitud httpservletRequest, httpservletResponse respuesta) arroja servletException, ioexception {respuesta.setContentType ("texto/html"); request.setcharacterEncoding ("UTF-8"); boolean isMultipart = servletFileUpload.IsmultipartContent (solicitud); String BasePath = GetServletContext (). GetRealPath ("/upload"); Archivo Basedirectory = nuevo archivo (BasePath); Cadena filename = ""; comienzo largo = 0; if (! BaseDirectory.IsDirectory ()) BaseIrectory.mkDirs (); if (isMultipart) {try {FileItemFactory factory = new DiskFileItemFactory (); ServletFileUpload upload = new ServLetFileUpload (fábrica); @SupessWarnings ("sin verificar") Lista <StilEitem> fileItems = upload.parserequest (solicitud); for (fileItem I: fileItems) {if (i.isformfield ()) {string name = i.getFieldName (); Valor de cadena = i.getString (); if (name.equals ("inicio")) start = long.parselong (i.getString ()); }} for (fileItem item: fileItems) {if (item.isformfield ()) continuar; filename = item.getFieldName (); if (mkdir (basepath)) {fileSonserver = createEfile (BasePath, FileName); if (fileonserver.length () == 0) {fileOutputStream fos = new FileOutputStream (FileServer, true); Ioutils.copy (item.getInputStream (), fos); } if (inicio> 0) {fileOutputStream fos = new FileOutputStream (FileServer, true); Ioutils.copy (item.getInputStream (), fos); } PrintWriter pw = respuesta.getWriter (); pw.write ("{/" longitud/":/" "+fileonserver.length ()+"/"}"); pw.flush (); }}} Catch (Exception e) {}}} privado Archivo createFile (string ruta, name de cadena) lanza ioexception {archivo tmp = nuevo archivo (ruta, nombre); if (! tmp.exists ()) {tmp.createenewfile (); } return tmp; } private boolean mkdir (ruta de cadena) {resultado boolean = true; Archivo tmp = nuevo archivo (ruta); if (! tmp.isDirectory ()) {result = tmp.mkdirs (); } resultado de retorno; }}2 、 Java 代码 :
var ajaxupload = function (e) { / ** * E URL Método Error de éxito de datos * / var xmlhttprequest; if (window.xmlhttprequest) {xmlhttprequest = new xmlhttprequest (); if (xmlhttprequest.overridemimeType) {xmlhttprequest.overridEmeType ("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]); romper; } catch (e) {return; }}} if (xmlhttprequest == Undefined || xmlhttprequest == null) {alert ("xmlhttprequest 对象创建失败!!"); devolver; } 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 !!!"); devolver; } if (e.url == null || e.url == Undefined) {e.Alert ("http 的请求地址必须设置!"); devolver; }} this.xmlhttp.onreadyStateChange = function () {if (this.readyState == 4) {if (this.status == 200) {var resphiseText = this.ResponseText; VAR Responsexml = this.RePonsexml; if (e.success == Undefined || e.success == null) {alert ("没有设置处理数据正确返回的方法"); alerta ("返回的数据 :" + ResponseExtext); } else {e.success (ResponseExtext, Responsexml); }} else {if (e.error == Undefined || E.Error == null) {alert ("没有设置处理数据返回失败的处理方法!"); alerta ("http 的响应码 :" + this.status + ", 响应码的文本信息 :" + this.statusText); } else {e.error (this.status, this.statusText); }}}} // var formhtm = "<form de formato = '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 ("salida")); data.append ("nombre", nombre de archivo); data.append ("inicio", e.data.start); data.append (nombre de archivo, 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 rath.substring (pos + 1);} function getFilesize (id) {return document.getElementById (id) .files [0] .size;}3 、 HTML 代码 :
<! Doctype html> <html> <fead> <meta http-equiv = "content-type" content = "text/html; charset = utf-8"> <script type = "text/javaScript" src = "test.js"> </script> </head> <body> <nume type = "file" name = "upload" up up up "up" value = "上传"/> <span> 请选择要上传的文件 (小于 1g) </span> <input type = "button" value = "上传" onClick = "test ();"/> <form id = "output" enctype = "multipart/form-data"> </form> <script> test () {ajaxupload ({id: "upload", url:: url:: "/Pcc/reston/ajaxupload", método: "post", data: {start: 0}, éxito: function (e) {var l = json.parse (e) .length. }, Error: Función (e) {console.log (e); } </script> </body> </html>以上就是本文的全部内容 希望对大家学习 希望对大家学习 java 程序设计有所帮助。