tydic_Java web項目中上傳檔案功能的程式碼範例__java

來源:互聯網
上載者:User
效果:

代碼: JSP

<li class="item db">                    <span class="tt">pos文檔:</span>                      <div class="file-line">                      <form id="dataform" action="${ctx}/uploadFileSftp" enctype="multipart/form-data" method="post">                        <input  type="text" id="viewfile" onmouseout="document.getElementById('file').style.display='none';" class="inputstyle" />                        <label for="unload" onmouseover="document.getElementById('file').style.display='block';" class="file1"></label>                        <input type="file" name="file" onchange="document.getElementById('viewfile').value=this.value;this.style.display='none';autoUploadFile()" class="file" id="file" />                     </form>                    </div>                </li>
JS:
function autoUploadFile(){    if(uploadFileCheck()){        $('#dataform').ajaxSubmit({            dataType: 'json',            success: function(data){                if(data.error != null && typeof(data.error) != "undefined"){                    alert(data.error);                }else{                    filePaths = data.info;                    alert(data.msg);                };            },            error: function(status, err){                console.info(status+","+err);                alert("status: "+status+" err: "+err);            }        })    }} 
function uploadFileCheck(){     var upload_file = $('#viewfile').val();     var fileTypes = new Array("pos","txt");     var fileTypeFlag = "0";     if(upload_file != ""){         var newFileName = upload_file.split('.');         newFileName = newFileName[newFileName.length-1];         for(var i=0;i<fileTypes.length;i++){             if(fileTypes[i] == newFileName){                 fileTypeFlag = "1";             }         };         if(fileTypeFlag == "0"){             alert("上傳檔案必須是pos、txt格式滴");             return false;         };         return true;     }else{         alert("請上傳檔案。");         return false;     }       }
JAVA
package com.tydic.unicom.res.web.busi.controller.resCard;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;import net.sf.json.JSONObject;import org.apache.log4j.Logger;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.ResponseBody;import org.springframework.web.multipart.MultipartFile;import org.springframework.web.multipart.MultipartHttpServletRequest;import com.jcraft.jsch.ChannelSftp;import com.jcraft.jsch.JSchException;import com.jcraft.jsch.SftpException;import com.tydic.unicom.res.web.busi.controller.config.GetToken;import com.tydic.unicom.res.web.busi.controller.config.SFTPChannelUtil;@Controllerpublic class FileUploadSftpController {    private static Logger logger = Logger.getLogger(FileUploadSftpController.class);     @RequestMapping(value="/uploadFileSftp",method=RequestMethod.POST)    @ResponseBody    public void uploadFileSftp(MultipartFile file,HttpServletRequest request,HttpServletResponse response,HttpSession session) throws IOException, JSchException, SftpException{        JSONObject jsonOut = new JSONObject();        request.setCharacterEncoding("utf-8");        response.setCharacterEncoding("utf-8");        String filePath = null;        if(request instanceof MultipartHttpServletRequest){            if(file.isEmpty()){                logger.info("檔案未上傳");                jsonOut.put("error", "上傳檔案內容為空白");                response.setContentType("text/html;charset=utf-8");                response.getWriter().print(jsonOut.toString());            }else{                logger.info("上傳檔案內容資訊:"+readFile(file.getInputStream()));                if(isValid(readFile(file.getInputStream()))){                    SFTPChannelUtil channel = new SFTPChannelUtil();                    ChannelSftp channelSftp = channel.getChannel(60000);                    filePath = GetToken.get("SFTP_REQ_LOC")+"/"+file.getOriginalFilename();                    logger.info("檔案上傳路徑:"+filePath);                    channelSftp.put(file.getInputStream(), filePath, ChannelSftp.OVERWRITE);//                  session.setAttribute("filePath", filePath);//                  request.setAttribute("filePath", filePath);                    jsonOut.put("msg", "檔案上傳成功。");                    jsonOut.put("info", filePath);                    response.setContentType("text/html;charset=utf-8");                    response.getWriter().print(jsonOut.toString());                }else{                    logger.info("檔案上傳失敗");                    jsonOut.put("msg", "檔案格式不正確,上傳失敗。");                    response.setContentType("text/html;charset=utf-8");                    response.getWriter().print(jsonOut.toString());                }            }        }    }    private static String readFile(InputStream in) throws IOException{        String number = "";        InputStreamReader reader = new InputStreamReader(in);        BufferedReader buffer = new BufferedReader(reader);        String tmp = null;        while((tmp = buffer.readLine()) != null){            number += tmp.replaceAll(" ", "");        }        return number;    }    private static boolean isValid(String str){        String regex = "^[a-z0-9A-Z]+$";        return str.matches(regex);    }}
擷取上傳檔案位置配置

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.