溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

web中如何解決文件上傳取不到真實(shí)路徑問題

發(fā)布時(shí)間:2021-10-19 14:40:53 來源:億速云 閱讀:185 作者:小新 欄目:web開發(fā)

這篇文章主要為大家展示了“web中如何解決文件上傳取不到真實(shí)路徑問題”,內(nèi)容簡(jiǎn)而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領(lǐng)大家一起研究并學(xué)習(xí)一下“web中如何解決文件上傳取不到真實(shí)路徑問題”這篇文章吧。

1、問題描述:

前一段時(shí)間要做一個(gè)excel數(shù)據(jù)導(dǎo)入到數(shù)據(jù)庫的功能,當(dāng)時(shí)用的是google chrome,沒有用form表單,僅僅一個(gè)<input type="file"/>組件,上傳excel時(shí)怎么也去不到文件路徑,不論是從哪個(gè)驅(qū)動(dòng)器上傳,文件路徑都是:c:\fakepath\文件名.xls。

2、解決方案

 網(wǎng)上轉(zhuǎn)悠了老半天,沒找到一個(gè)完美的方案,最后經(jīng)個(gè)同事指導(dǎo):

利用一個(gè)js(插件)ajaxfileupload.js,源碼放到最后面,先看具體代碼:

jsp:

<div class="rcon">
                                                    
<a href="download/subcompany.xls" >下載號(hào)碼模板</a>
<br />
<hr />
<input id="newfile" name="newfile" type="hidden" />
選擇文件:
<input type="file" id="subfile" name="subfile" />
<br />
<input type="button" value="導(dǎo)入" id="importsub" />
</div>

注意: file input的name屬性必須的,后面要用.

js代碼:(17行用到了input的name屬性)

文件上傳到: url : '<%=webapp%>' '/FileUpload?path=file/share',這里用了servlet(該servlet對(duì)FileUpload路徑進(jìn)行攔截)

當(dāng)然可以用action

$.ajaxFileUpload方法的成功回調(diào)方法有參數(shù)data及status,其中從data可以得知上傳上去的文件的名字:文件名=data.img

function uploadfile() {
    var upload_file = $("#subfile").val();
    if (upload_file == null || upload_file == undefined || upload_file == "") {
        Showbo.Msg.alert('系統(tǒng)提示:請(qǐng)選擇要上傳的文件!');
        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('系統(tǒng)提示:' + e);
            return false;
        }
        });
    }
}

當(dāng)然靠上面的不夠的,真正上傳的幕后是(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");
        }      
        // 設(shè)置文件存儲(chǔ)位置
        factory.setRepository(new File(path));
        // 設(shè)置大小,如果文件小于設(shè)置大小的話,放入內(nèi)存中,如果大于的話則放入磁盤中
        factory.setSizeThreshold(1024 * 1024);
        ServletFileUpload upload = new ServletFileUpload(factory);
        // 這里就是中文文件名處理的代碼,其實(shí)只有一行,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());//獲取當(dāng)前時(shí)間  
        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中如何解決文件上傳取不到真實(shí)路徑問題”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對(duì)大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

web
AI