javaweb实现文件上传,前端与后台的结合实现
大家好,這是原創(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))
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)您選擇上傳文件: <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>上傳情況: <span id="pn"></span></div><br> <input type="button" value="上傳" onclick="dealfile(fileform)" /> <input type="reset" value="重新上傳(重置)" /></form>Java后臺(tái):(注意與前端文件名字的統(tǒng)一)
1.一個(gè)輸出session的process的jsp(簡(jiǎn)單)
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)題。
- 上一篇: 关于eclipse中web项目tomca
- 下一篇: 修改注册表设置默认浏览器