In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-21 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly shows you the "web how to solve the file upload can not be the real path problem", the content is easy to understand, clear, hope to help you solve the doubt, the following let the editor lead you to study and learn "how to solve the file upload in web can not get the real path problem" this article.
1. Problem description:
Some time ago, I wanted to import excel data into the database. At that time, I used google chrome, and I didn't use form forms. Just one component, I couldn't get to the file path when uploading excel. No matter which drive I uploaded, the file path was: C:\ fakepath\ file name .xls.
2. Solution
After wandering around the Internet for a long time, I couldn't find a perfect plan, and finally got the guidance of a colleague:
Using a js (plug-in) ajaxfileupload.js, put the source code at the end. Look at the specific code first:
Jsp:
Download the number template selection file:
Note: the name attribute of file input is required and will be used later.
Js code: (line 17 uses the name attribute of input)
The file is uploaded to: url:'+'/ FileUpload?path=file/share', where servlet is used (the servlet intercepts the FileUpload path)
Of course you can use action.
The successful callback method of the $.ajaxFileUpload method includes parameters data and status, in which you can know the name of the uploaded file from data: file name = data.img
Function uploadfile () {var upload_file = $("# subfile"). Val (); if (upload_file = = null | | upload_file = = undefined | | upload_file = "") {Showbo.Msg.alert ('system prompt: please select a file to upload!'); return false;} else {var file = upload_file.split ('.'); var suffix = file [file.length-1] If (suffix! = 'xls') {Showbo.Msg.alert (' file format must be: xls'); return;} / / $("# fileReal") .val (upload_file) $.ajaxFileUpload ({url:''+'/ FileUpload?path=file/share', secureuri: true, fileElementId: 'subfile', dataType:' json', success: function (data Status) {$('# pic') .attr ({src:'/ file/share/' + data}) $('# newfile') .val (data.img); var filename = data.img; importSubNum (filename); / / $('# pubbt'). Click (); / * $('# form1'). Submit (); * / * Showbo.Msg.alert ('file uploaded successfully!') ; * /}, error: function (data, status, e) {Showbo.Msg.alert ('system prompt:' + e); return false;}});}}
Of course, it is not enough to rely on the above. The real upload is (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 / * upload 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 (paramorphic null) {path = request.getRealPath (param);} else {path = request.getRealPath (" / p_w_picpaths ");} / / sets the file storage location factory.setRepository (new File (path)) / / set the size. If the file is smaller than the set size, put it in memory, and if it is larger, put it on disk factory.setSizeThreshold (1024 * 1024); ServletFileUpload upload = new ServletFileUpload (factory); / / here is the code for processing Chinese file names. In fact, there is only one line, serheaderencoding can upload.setHeaderEncoding ("gbk") Try {List 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 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 DocumentjQuery.extend({ createUploadIframe: function(id, uri) { //create frame var frameId = 'jUploadFrame' + id; if(window.ActiveXObject) { var io = document.createElement(''); 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(''); 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[xss_clean]: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[xss_clean]: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 (") .html (data). EvalScripts () } return data;}}). These are all the contents of this article entitled "how to solve the problem that the real path cannot be uploaded to a file in web". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.