日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 前端技术 > HTML >内容正文

HTML

javaweb实现文件上传,前端与后台的结合实现

發(fā)布時(shí)間:2024/4/18 HTML 37 豆豆
生活随笔 收集整理的這篇文章主要介紹了 javaweb实现文件上传,前端与后台的结合实现 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

大家好,這是原創(chuàng)的文件上傳源碼哦。
希望給大家?guī)?lái)參考價(jià)值。
閱讀注意:
1.只給出了關(guān)鍵代碼(但是絕大部分代碼),需要自己小小潤(rùn)色一下。
2.代碼分為前端與后臺(tái),
3.本人初學(xué)者,有錯(cuò),望您指出。
4.后臺(tái)需要jar包支持:
commons-io-1.3.2.jar
commons-fileupload-1.2.1.jar
5.表單屬性設(shè)置:
enctype=“multipart/form-data”
ajax請(qǐng)求頭設(shè)置:
this.httpRequest.setRequestHeader(“Content-Disposition”,“multipart/form-data”);

前端代碼:
采用ajax獲取(自己寫(xiě)的ajax,原理性強(qiáng)):
ajax.js(ajax重構(gòu))

/*** Ajax重構(gòu) 多次使用,代碼重構(gòu)*/ var timer = null; var net = new Object(); // ajax重構(gòu) net.AjaxRequest = function(url, dealfun, onerror, method, params) {// 創(chuàng)建XMLHttpRequestthis.httpRequest = null;// 回調(diào)函數(shù)this.onload = dealfun;// 錯(cuò)誤處理this.onerror = (onerror) ? onerror : this.defaultError;// 向服務(wù)器發(fā)送請(qǐng)求(創(chuàng)建連接)this.loadrequest(url, method, params);} // 向服務(wù)器發(fā)送請(qǐng)求(創(chuàng)建連接) net.AjaxRequest.prototype.loadrequest = function(url, method, params) {// 創(chuàng)建XMLHttpRequestif (window.XMLHttpRequest)this.httpRequest = new XMLHttpRequest();else if (window.ActiveXObject)this.httpRequest = new ActiveXObject("Microsoft.XMLHTTP");if (this.httpRequest) {try {// 回調(diào)函數(shù)var deal = this;this.httpRequest.onreadystatechange = function() {net.AjaxRequest.deal.call(deal);};// 創(chuàng)建XMLHttpRequest成功,發(fā)送請(qǐng)求this.httpRequest.open(method, url, true);this.httpRequest.setRequestHeader("Content-Disposition","multipart/form-data");// 發(fā)送paramsthis.httpRequest.send(params);} catch (e) {this.onerror.call(this);}} } //回調(diào) net.AjaxRequest.deal = function() {if (this.httpRequest.readyState == 4)if (this.httpRequest.status == 200)this.onload.call(this);elsethis.onerror.call(this); } // 默認(rèn)錯(cuò)誤處理 net.AjaxRequest.prototype.defaultError = function() {alert("默認(rèn)錯(cuò)誤處理:回調(diào)狀態(tài)碼:" + this.httpRequest.readyState + "錯(cuò)誤狀態(tài)碼:"+ this.httpRequest.status); // window.clearInterval(timer); // timer = null; }

html.js(前端頁(yè)面js)

var timer = null; // 上傳文件處理結(jié)果回調(diào),ajax,json,原型 function dealupload() {var p = this.httpRequest.responseText;var p1 = p.substr(0, 5);if (p1 == "完成上傳!") {clearInterval(timer);timer = null;alert(p1);return true;} else {document.getElementById("pn").innerHTML = p;document.getElementById("pg").style.width = (p1 * (500 / 100)).toString()+ "px";} }// 上傳文件 function doupload() {var load = new net.AjaxRequest("showprocess.jsp?nocache="+ new Date().getTime(), dealupload, null, "POST");} function dealcancelupload() {alert("你取消了上傳此文件!!!"); } // 取消文件上傳 fileform.onreset = function() {document.getElementById("pg").style.width = "0px";var no = new net.AjaxRequest("cancelupload.jsp?nocache="+ new Date().getTime(), dealcancelupload, null, "POST"); }// 文件預(yù)處理上傳 function dealfile(fileform) {var file = document.getElementById("file");if (document.fileform.file.value == "") {alert("請(qǐng)選擇上傳文件!!!");return false;}var filesize = file.files[0].size;if (filesize > 2000 * 1024 * 1024) {alert("請(qǐng)選擇小于2000MB的文件!!!");return false;} else {timer = window.setInterval("doupload()", 300);fileform.submit();} }

前端表單代碼(記得引入以上js!!!):

`<form id="fileform" method="post" action="UploadFile" name="fileform" enctype="multipart/form-data"><br> <%=session.getAttribute("user")+" " %>請(qǐng)您選擇上傳文件:&nbsp;&nbsp;&nbsp;&nbsp; <input type="file" name="file" id="file" style="border: 1px solid; margin: 5px; background-color: #eeeeee;" /> <br> <br><div style="text-align: left; margin-left: 120px;"><div>注意:文件不能大于2000M,登錄后在傳文件</div>當(dāng)前上傳進(jìn)度:<div style="border-radius:30px;margin-top: 10px; background-color: #aaeeaa; height: 20px; width: 500px; border: 2px solid snow"><div style="border-radius:30px;background-color: black; height: 20px; width: 0px;" id="pg"></div></div>上傳情況:&nbsp; <span id="pn"></span></div><br> <input type="button" value="上傳" onclick="dealfile(fileform)" /> &nbsp;&nbsp;&nbsp;&nbsp; <input type="reset" value="重新上傳(重置)" /></form>

Java后臺(tái):(注意與前端文件名字的統(tǒng)一)
1.一個(gè)輸出session的process的jsp(簡(jiǎn)單)

`<body><%response.getWriter().write(session.getAttribute("process").toString());%> </body>`

2.一個(gè)獲取session的cancel的jsp(簡(jiǎn)單)

<body> <% session.setAttribute("cancel", "true"); %> </body>

`

3.上傳類(lèi):

package com.uploadfile; import java.io.*; import javax.servlet.*; import java.util.Iterator; import java.util.List; import org.apache.tomcat.util.http.fileupload.*; @WebServlet(name = "UploadFile", value = "/UploadFile") public class UploadFile extends HttpServlet {private static final long serialVersionUID = 1L;@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {// TODO 自動(dòng)生成的方法存根this.uploadfile(req, resp);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {// TODO 自動(dòng)生成的方法存根this.uploadfile(req, resp);}@Overrideprotected void service(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException {// TODO 自動(dòng)生成的方法存根super.service(arg0, arg1);}@Overridepublic void destroy() {// TODO 自動(dòng)生成的方法存根super.destroy();}@SuppressWarnings("rawtypes")public void uploadfile(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//解決亂碼req.setCharacterEncoding("UTF-8");resp.setCharacterEncoding("UTF-8");HttpSession session = req.getSession();//取消文件上傳標(biāo)志session.setAttribute("cancel", "false");//錯(cuò)誤信息String error = "";//前端響應(yīng)session.setAttribute("process", "瀏覽器上傳文件中...請(qǐng)耐心等待");//創(chuàng)建DiskFileItemFactory fac = new DiskFileItemFactory();ServletFileUpload upl = new ServletFileUpload(fac);try {// 解析時(shí)間需更新客戶端是否取消上傳List items = upl.parseRequest(new ServletRequestContext(req));Iterator it = items.iterator();while (it.hasNext()) {FileItem item = (FileItem) it.next();if (!item.isFormField()) {if (item.getName() != null && !item.getName().equals("")) {long loadsize = item.getSize();String name = item.getName();File temp1 = new File(name);//服務(wù)器創(chuàng)建寫(xiě)入文件File temp = new File(req.getSession().getServletContext().getRealPath("/LoadFile"), temp1.getName());// 存入文件// 客戶端上傳文件讀取InputStream tempr = item.getInputStream();byte[] b = new byte[1024];// 上傳文件存入服務(wù)器FileOutputStream wf = new FileOutputStream(temp);// 上傳進(jìn)度double process = 0;int length = 0;boolean flag = true;while ((length = tempr.read(b)) != -1) {if (session.getAttribute("cancel") == "true") {//如果取消了上傳session.setAttribute("cancel", "false");session.setAttribute("process", "取消上傳中。");wf.flush();wf.close();flag = false;if (temp.exists()) {temp.delete();}break;}process += (length / (double) loadsize) * 100D;wf.write(b);session.setAttribute("process", "服務(wù)器寫(xiě)入進(jìn)度:"+(float) process + "%");}if (flag == true) {wf.flush();wf.close();session.setAttribute("process", "完成上傳!");}Thread.sleep(500);}}}} catch (Exception e) {// TODO 自動(dòng)生成的 catch 塊e.printStackTrace();error = "服務(wù)器出錯(cuò)";}if (!error.equals("")) {session.setAttribute("process", error + "->失敗");try {Thread.sleep(1000);} catch (InterruptedException e) {// TODO 自動(dòng)生成的 catch 塊}}//完成服務(wù)重定向//req.getRequestDispatcher("WEB-INF/login/welcome.jsp").forward(req, resp);}}

完結(jié)。

總結(jié)

以上是生活随笔為你收集整理的javaweb实现文件上传,前端与后台的结合实现的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。