您好,登錄后才能下訂單哦!
這篇文章主要為大家展示了“web中如何解決文件上傳取不到真實路徑問題”,內容簡而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領大家一起研究并學習一下“web中如何解決文件上傳取不到真實路徑問題”這篇文章吧。
1、問題描述:
前一段時間要做一個excel數據導入到數據庫的功能,當時用的是google chrome,沒有用form表單,僅僅一個<input type="file"/>組件,上傳excel時怎么也去不到文件路徑,不論是從哪個驅動器上傳,文件路徑都是:c:\fakepath\文件名.xls。
2、解決方案
網上轉悠了老半天,沒找到一個完美的方案,最后經個同事指導:
利用一個js(插件)ajaxfileupload.js,源碼放到最后面,先看具體代碼:
jsp:
<div class="rcon"> <a href="download/subcompany.xls" >下載號碼模板</a> <br /> <hr /> <input id="newfile" name="newfile" type="hidden" /> 選擇文件: <input type="file" id="subfile" name="subfile" /> <br /> <input type="button" value="導入" id="importsub" /> </div>
注意: file input的name屬性必須的,后面要用.
js代碼:(17行用到了input的name屬性)
文件上傳到: url :
'<%=webapp%>'
+
'/FileUpload?path=file/share',這里用了servlet(該servlet對FileUpload路徑進行攔截)
當然可以用action
$.ajaxFileUpload方法的成功回調方法有參數data及status,其中從data可以得知上傳上去的文件的名字:文件名=data.img
function uploadfile() { var upload_file = $("#subfile").val(); if (upload_file == null || upload_file == undefined || upload_file == "") { Showbo.Msg.alert('系統提示:請選擇要上傳的文件!'); return false; } else { var file = upload_file.split('.'); var suffix = file[file.length - 1]; if (suffix != 'xls') { Showbo.Msg.alert('文件格式必須是:xls'); return; } // $("#fileReal").val(upload_file); $.ajaxFileUpload( { url : '<%=webapp%>' + '/FileUpload?path=file/share', secureuri : true, fileElementId : 'subfile', dataType : 'json', success : function(data, status) { $('#pic').attr( { src : '<%=webapp%>/file/share/' + data }); $('#newfile').val(data.img); var filename = data.img; importSubNum(filename); //$('#pubbt').click(); /* $('#form1').submit();*/ /*Showbo.Msg.alert('文件上傳成功!');*/ }, error : function(data, status, e) { Showbo.Msg.alert('系統提示:' + e); return false; } }); } }
當然靠上面的不夠的,真正上傳的幕后是(servlet):
package com.hg.sale.service.upload; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.sf.json.JSONObject; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.log4j.Logger; /** * 上傳Service * * @author lvzhibo * */ public class FileUpload extends HttpServlet { static Logger logf=Logger.getLogger(FileUpload.class); private static final long serialVersionUID = 1L; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { DiskFileItemFactory factory = new DiskFileItemFactory(); String param=request.getParameter("path"); String rename=request.getParameter("rename"); String name=request.getParameter("name"); String log=request.getParameter("log"); String path =""; if(param!=null){ path = request.getRealPath(param); }else{ path = request.getRealPath("/p_w_picpaths"); } // 設置文件存儲位置 factory.setRepository(new File(path)); // 設置大小,如果文件小于設置大小的話,放入內存中,如果大于的話則放入磁盤中 factory.setSizeThreshold(1024 * 1024); ServletFileUpload upload = new ServletFileUpload(factory); // 這里就是中文文件名處理的代碼,其實只有一行,serheaderencoding就可以了 upload.setHeaderEncoding("gbk"); try { List<FileItem> items = upload.parseRequest(request); for (FileItem item : items) { if (item.isFormField()) { } else { String fileName = item.getName(); if (fileName != null) { int pos = fileName.lastIndexOf("\\"); if (pos + 1 < fileName.length()) { fileName = fileName.substring(pos + 1); } } //author xuzijin 6.19 自定義圖片名稱 File fpath=new File(path); if(!fpath.exists()){ fpath.mkdir(); } if(name!=null&&rename!=null){ String[] str=fileName.split("\\."); int rnm=Integer.parseInt(rename); if(rnm<=4){ fileName=name+"_main_"+rename+"."+str[1]; }else{ int rn=rnm-4; fileName=name+"_icon_"+rn+"."+str[1]; } } if(name==null&&rename!=null){ String[] str=fileName.split("\\."); int rnm=Integer.parseInt(rename); String imgName=""; switch(rnm){ case 2001: imgName="attr_1"; break; case 2002: imgName="attr_2"; break; case 2003: imgName="attr_3"; break; case 2004: imgName="attr_4"; break; case 2005: imgName="attr_5"; break; case 2006: imgName="attr_6"; break; case 2007: imgName="attr_7"; break; case 2008: imgName="attr_8"; break; } fileName=imgName+"."+str[1]; } if(rename==null&&name==null&&log==null){ fileName=getTime()+getExtensionName(fileName); } /*if(rename==null&&name==null&&log.equals("time")){ fileName= getFileName(fileName)+getTime()+getExtensionName(fileName); }*/ response.setContentType("text/html"); response.setCharacterEncoding("gbk"); item.write(new File(path, fileName)); PrintWriter out = response.getWriter(); JSONObject obj=new JSONObject(); obj.put("img", fileName); out.println(obj.toString()); logf.info("xml="+(obj.toString())); } } } catch (FileUploadException e) { response.getWriter().print(e.toString()); } catch (Exception e) { e.printStackTrace(); response.getWriter().print(e.toString()); } } public String getExtensionName(String filename) { if ((filename != null) && (filename.length() > 0)) { int dot = filename.lastIndexOf('.'); if ((dot >-1) && (dot < (filename.length() - 1))) { return filename.substring(dot); } } return filename; } public String getTime(){ SimpleDateFormat formatter = new SimpleDateFormat ("yyyyMMddhh34mmss"); Date curDate = new Date(System.currentTimeMillis());//獲取當前時間 String str = formatter.format(curDate); return str; } public String getFileName(String filename) { if ((filename != null) && (filename.length() > 0)) { int dot = filename.lastIndexOf('.'); if ((dot >-1) && (dot < (filename.length() - 1))) { return filename.substring(0,dot-1); } } return filename; } }
ajaxfileupload.js
// JavaScript Document jQuery.extend({ createUploadIframe: function(id, uri) { //create frame var frameId = 'jUploadFrame' + id; if(window.ActiveXObject) { var io = document.createElement('<iframe id="' + frameId + '" name="' + frameId + '" />'); if(typeof uri== 'boolean'){ io.src = 'javascript:false'; } else if(typeof uri== 'string'){ io.src = uri; } } else { var io = document.createElement('iframe'); io.id = frameId; io.name = frameId; } io.style.position = 'absolute'; io.style.top = '-1000px'; io.style.left = '-1000px'; document.body.appendChild(io); return io; }, createUploadForm: function(id, fileElementId) { //create form var formId = 'jUploadForm' + id; var fileId = 'jUploadFile' + id; var form = jQuery('<form action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>'); var oldElement = jQuery('#' + fileElementId); var newElement = jQuery(oldElement).clone(); jQuery(oldElement).attr('id', fileId); jQuery(oldElement).before(newElement); jQuery(oldElement).appendTo(form); //set attributes jQuery(form).css('position', 'absolute'); jQuery(form).css('top', '-1200px'); jQuery(form).css('left', '-1200px'); jQuery(form).appendTo('body'); return form; }, ajaxFileUpload: function(s) { // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout s = jQuery.extend({}, jQuery.ajaxSettings, s); var id = s.fileElementId; var form = jQuery.createUploadForm(id, s.fileElementId); var io = jQuery.createUploadIframe(id, s.secureuri); var frameId = 'jUploadFrame' + id; var formId = 'jUploadForm' + id; if( s.global && ! jQuery.active++ ) { // Watch for a new set of requests jQuery.event.trigger( "ajaxStart" ); } var requestDone = false; // Create the request object var xml = {}; if( s.global ) { jQuery.event.trigger("ajaxSend", [xml, s]); } var uploadCallback = function(isTimeout) { // Wait for a response to come back var io = document.getElementById(frameId); try { if(io.contentWindow) { xml.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null; xml.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document; }else if(io.contentDocument) { xml.responseText = io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null; xml.responseXML = io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document; } }catch(e) { jQuery.handleError(s, xml, null, e); } if( xml || isTimeout == "timeout") { requestDone = true; var status; try { status = isTimeout != "timeout" ? "success" : "error"; // Make sure that the request was successful or notmodified if( status != "error" ) { // process the data (runs the xml through httpData regardless of callback) var data = jQuery.uploadHttpData( xml, s.dataType ); if( s.success ) { // ifa local callback was specified, fire it and pass it the data s.success( data, status ); }; if( s.global ) { // Fire the global callback jQuery.event.trigger( "ajaxSuccess", [xml, s] ); }; } else { jQuery.handleError(s, xml, status); } } catch(e) { status = "error"; jQuery.handleError(s, xml, status, e); }; if( s.global ) { // The request was completed jQuery.event.trigger( "ajaxComplete", [xml, s] ); }; // Handle the global AJAX counter if(s.global && ! --jQuery.active) { jQuery.event.trigger("ajaxStop"); }; if(s.complete) { s.complete(xml, status); } ; jQuery(io).unbind(); setTimeout(function() { try { jQuery(io).remove(); jQuery(form).remove(); } catch(e) { jQuery.handleError(s, xml, null, e); } }, 100); xml = null; }; } // Timeout checker if( s.timeout > 0 ) { setTimeout(function(){ if( !requestDone ) { // Check to see ifthe request is still happening uploadCallback( "timeout" ); } }, s.timeout); } try { var form = jQuery('#' + formId); jQuery(form).attr('action', s.url); jQuery(form).attr('method', 'POST'); jQuery(form).attr('target', frameId); if(form.encoding) { form.encoding = 'multipart/form-data'; } else { form.enctype = 'multipart/form-data'; } jQuery(form).submit(); } catch(e) { jQuery.handleError(s, xml, null, e); } if(window.attachEvent){ document.getElementById(frameId).attachEvent('onload', uploadCallback); } else{ document.getElementById(frameId).addEventListener('load', uploadCallback, false); } return {abort: function () {}}; }, uploadHttpData: function( r, type ) { var data = !type; data = type == "xml" || data ? r.responseXML : r.responseText; // ifthe type is "script", eval it in global context if( type == "script" ) { jQuery.globalEval( data ); } // Get the JavaScript object, ifJSON is used. if( type == "json" ) { eval( "data = " + data ); } // evaluate scripts within html if( type == "html" ) { jQuery("<div>").html(data).evalScripts(); } return data; } });
以上是“web中如何解決文件上傳取不到真實路徑問題”這篇文章的所有內容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內容對大家有所幫助,如果還想學習更多知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。