本文实例为大家分享了 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; Importer javax.servlet.servletconfig; import javax.servlet.servletException; importer javax.servlet.annotation.webservlet; import javax.servlet.http.httpservlet; import javax.servlet.http.httplerserponsest; 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") classe publique ajaxupload étend httpsservlet {@Override public void init (servletconfig config) lève ServletException {// Todo généré par la méthode Stub super.init (config); } @Override Protected Void Service (HttpServletRequest Request, HttpServletResponse Response) lève ServletException, ioException {réponse.SetContentType ("Text / Html"); request.SetcharAtterencoding ("UTF-8"); booléen isMultupart = servletFileupload.ismulTipartContent (demande); String basepath = getServletContext (). GetRealPath ("/ upload"); File-BasedIrGory = nouveau fichier (basepath); String filename = ""; START long = 0; if (! Base-BasedIrectory.isDirectory ()) BasedIrectory.mkDirs (); if (isMultupart) {try {fileItemfactory factory = new DiskFileItemFactory (); ServletFileUpload upload = new ServletFileUpload (Factory); @SuppressWarnings ("Unchecked") List <FichierItem> FileItems = upload.parseRequest (demande); for (fileItem i: fileItems) {if (i.isformField ()) {String name = i.getFieldName (); String Value = i.getString (); if (name.equals ("start")) start = long.parselong (i.getString ()); }} pour (FileItem Item: FileItems) {if (item.isformField ()) continu; 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 = réponse.getWriter (); pw.write ("{/" longueur / ": /" "+ fileonServer.length () +" / "}"); pw.flush (); }}} catch (exception e) {}}} Private File CreateFile (String Path, String Name) lève ioException {File tmp = new File (path, nom); if (! tmp.exists ()) {tmp.createenewfile (); } return tmp; } private booléen mkdir (chemin de chaîne) {booléen result = true; Fichier tmp = nouveau fichier (chemin); if (! tmp.isdirectory ()) {result = tmp.mkDirs (); } Retour Résultat; }}2 、 Java 代码 :
var ajaxupload = function (e) {/ ** * Erl de la méthode URL Erreur de réussite des données * / 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]); casser; } catch (e) {return; }}} if (xmlHttpRequest == Undefined || xmlHttpRequest == null) {alert ("xmlhttprequest 对象创建失败!!"); retour; } else {this.xmlhttp = xmlHttpRequest; } var fichier = 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 !!!"); retour; } if (e.Url == null || e.url == undefined) {e.Alert ("http 的请求地址必须设置!"); retour; }} this.xmlhttp.onreadystateChange = function () {if (this.readystate == 4) {if (this.status == 200) {var ResponseText = this.ResponSExt; var réponsexml = this.reponsexml; if (e.success == Undefined || e.success == null) {alert ("没有设置处理数据正确返回的方法"); alert ("返回的数据 :" + ResponseText); } else {e.success (ResponseText, réponsexml); }} 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 ("sortie")); data.append ("nom", nom de fichier); 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);} fonction 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);} fonction getFileSize (id) {return document.getElementById (id) .files [0] .size;}3 、 HTML 代码 :
<! Doctype html> <html> <éadf> <méta http-equiv = "contenu-type" contenu = "text / html; charset = utf-8"> <script type = "text / javascript" src = "test.js"> </ script> </ad> <body> <entrée = "file" nom = "upload" id = upfoth " Value = "上传" /> <span> 请选择要上传的文件 (小于 1g) </span> <input type = "Button" value = "上传" onclick = "test ();" /> <form id = "output" enctype = "multipart / form-data"> </ form> <cript> function test () {ajaxupload ({id: "upload", url "Post", données: {start: 0}, succès: fonction (e) {var l = json.parse (e) .length; });}, erreur: fonction (e) {console.log (e); } </ script> </ body> </html>以上就是本文的全部内容 , 希望对大家学习 Java 程序设计有所帮助。