本文实例为大家分享了 Java 实现文件上传的具体代码 , 具体内容如下
1 、 java 代码 :
пакет com.github.reston.servlet; Импорт java.io.file; import java.io.fileOutputStream; импорт java.io.ioexception; импорт java.io.printwriter; import java.util.iterator; import java.util.list; Import javax.servlet.servletConfig; Import javax.servlet.servletexception; импорт javax.servlet.annotation.webservlet; импорт javax.servlet.http.httpservlet; import javax.servlet.http.httplectrequest. Импорт org.apache.commons.fileupload.fileitem; import org.apache.commons.fileupload.fileitemfactory; import org.apache.commons.fileupload.disk.diskfileTemFactory; import.Apache.commons.fileuD.Servale.Servale..commons.iLeSpaleSpload; @Webservlet ("/ajaxupload") открытый класс Ajaxupload расширяет httpservlet {@override public void init (конфигурация ServletConfig) THRES ServletException {// TODO Auto GENERED-METHOURE SUPER.INIT (config); } @Override Protected void Service (httpservlectrequest, httpservletresponse response) throws servletexception, ioexception {response.setContentType ("text/html"); request.setcharacterencoding ("UTF-8"); Boolean Ismultipart = ServletFileUpload.ismultipartContent (запрос); String basePath = getServletContext (). GetRealPath ("/upload"); File basedirectory = new File (BasePath); String filename = ""; Long Start = 0; if (! basederectory.isdirectory ()) basedirectory.mkdirs (); if (ismultipart) {try {fileitemfactory factory = new DiskFileItemFactory (); ServletFileUpload upload = new ServletFileUpload (Factory); @Suppresswarnings ("unchecked") list <fieleItem> 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 ()) продолжить; filename = item.getfieldname (); if (mkdir (basepath)) {file fileonserver = createfile (basepath, имя файла); 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) thrifes 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 Ошибка успеха данных * / 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]); перерыв; } catch (e) {return; }}} if (xmlhttprequest == undefined || xmlhttprequest == null) {alert ("xmlhttprequest 对象创建失败!!"); возвращаться; } 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 !!!); возвращаться; } if (e.url == null || e.url == undefined) {e.alert ("http 的请求地址必须设置!"); возвращаться; / var responsexml = this.reponsexml; if (e.success == undefined || e.success == null) {alert ("没有设置处理数据正确返回的方法"); Alert ("返回的数据 :" + responseText); } else {e.success (responsetext, responsexml); }} else {if (e.error == не определено || e.error == null) {alert ("没有设置处理数据返回失败的处理方法!"); Alert ("http 的响应码 :" + this.status + ", 响应码的文本信息 :" + this.statustext); } else {e.error (this.status, this.statustext); }}}} // var formhtm = "<form id = 'output' ectype = '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", имя файла); data.append ("start", e.data.start); data.append (имя файла, 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). 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 = "файл" name = "uplload" = uplload "=" uplload "=" uplload "=" uplload "=" uplload "=" uplload "=" uplload "=" uplload "=" uplload "=" uplload "</gup> <body> <input =" value = "上传"/> <pan> 请选择要上传的文件 (小于 1g) </span> <input type = "value =" 上传 "onclick =" test (); "/> <form id =" output "ectype =" multipart/form-data "> </form> <script> function test () {ajaxUpload ({id:", upload ", url: url: url: url: url: url: "/PCC/Reston/AjaxUpload", метод: "post", data: {start: 0}, успех: функция (e) {var l = json.parse (e) .length; : function (e) {console.log (e); } </script> </body> </html>以上就是本文的全部内容 , 希望对大家学习 java 程序设计有所帮助。