效果:
代碼: 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); }}
擷取上傳檔案位置配置