码迷,mamicode.com
首页 > Web开发 > 详细

上传文件功能-1

时间:2016-05-07 08:32:19      阅读:316      评论:0      收藏:0      [点我收藏+]

标签:

效果:

技术分享

代码:

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;

@Controller
public 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);
    }
}
获取上传文件位置配置

技术分享

上传文件功能-1

标签:

原文地址:http://blog.csdn.net/yhj19920417/article/details/51330771

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!