这篇文章主要为大家展示了“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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。