SpringMvc上传文件

  • 1.在前端jsp页面这样定义:
  • 注释:在jsp页面通过form表单上传文件,需要在form标签里面加一个enctype="multipart/form-data" 属性,另外method需要是post方式,还有就是需要在jsp页面加一个jquery.form.js的js才能使用下边ajaxForm的方式提交页面的数据
  • <form  action="<%=basePath%>KafkaManage/saveKafkaParameterSet.do" id="kafkaParameterForm" method="POST" enctype="multipart/form-data" >
     <li><span class="inp_tit">安装文件上传:</span><span class="inp_i"><input name="myFile" id="myFile" type="file" /></span></li>
    <div class="b_green" id="add" >
    <a href="javascript:;" id="saveKafkaParameterSet"><div class="b_green_left"></div>
    <div class="b_green_right">保 存</div></a>
    </div>
    
    </form>
    <script>
    $("#saveKafkaParameterSet").click(function(){
    $("#kafkaParameterForm").submit();
    layer.load('添加中,请稍等...');
    return false;
    });
    
    $("#kafkaParameterForm").ajaxForm({
    success: function(data) {
    data=data.replace(/<[^>]+>/g,"")
    layer.close(1);
    if (data == '1') {
    layer.msg('上传成功!', 3,{
    type:9,
    rate: 'top',
    shade: [0]
    });
    }else {
    layer.msg('上传失败!');
    }
    },
    error:function(){
    layer.close(1);
    layer.msg("服务器出错,请联系管理员");
    }
    })
    
    </script>

     

  • 2.在SpringMvc Controller层这样定义:
  • 注释:需要先上传到tomcat服务器,然后从tomcat服务器上传到其他的机器(这里引用了FileUploadUtils类、LinuxUtils(这两个类下边有~))
  • @ResponseBody
    @RequestMapping("/saveKafkaParameterSet")
    public String saveKafkaParameterSet(KafkaParameterSet kafkaParameterSet,@ModelAttribute("id2") String id2,MultipartFile myFile,HttpSession session){
    try{
    StreamUser user=(StreamUser)session.getAttribute("user");
    List<KafkaParameterSet> queryAllKafkaParameterSetByClusterName=kafkaParameterSetService.queryAllKafkaParameterSetByClusterName(kafkaParameterSet.getClusterName());
    if(queryAllKafkaParameterSetByClusterName.size()>0){
    return "2";//集群名称重复
    }else{
    if(null!=myFile&&!myFile.isEmpty()){
    FileUploadUtils fileUploadUtils = new FileUploadUtils();
    boolean tag = fileUploadUtils.fileUpload(myFile, myFile.getContentType(), myFile.getOriginalFilename(), PagePathByNGINX.kafkaParameterSet);
    KafkaUploadFile kafkaUploadFile=new KafkaUploadFile();
    kafkaUploadFile.kafkaUploadFile(kafkaParameterSet,myFile,session);
    }
    KafkaParameterSet kpm = kafkaParameterSetService.queryKafkaParameterSet();
    String kafkaiPs=kafkaParameterSet.getIps();
    String[] ips=kafkaiPs.split(",");
    Date date=new Date();
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String operatioinTime= formatter.format(date);
    kafkaParameterSet.setOperatorTime(operatioinTime);
    kafkaParameterSet.setOperatorUser("storm");///改成登陆时的操作人
    kafkaParameterSetService.saveKafkaDetail(kafkaParameterSet);
    for(int i=0;i<ips.length;i++){
    KafkaBaseConfInfo kafkaBaseConfInfo=new KafkaBaseConfInfo();
    kafkaBaseConfInfo.setIp(ips[i]);
    kafkaBaseConfInfo.setPort(9092);
    kafkaBaseConfInfo.setHost(ips[i]);
    kafkaBaseConfInfo.setPartitionNum(ips.length);
    kafkaBaseConfInfo.setDataStorageTime("48");
    kafkaBaseConfInfo.setIsAutoBuildTopic(0);
    kafkaBaseConfInfo.setZkTimeout(1000000);
    kafkaBaseConfInfo.setBrokerID(i + 1 + 1);
    kafkaBaseConfInfo.setZkPort("2181");
    kafkaBaseConfInfo.setUserName(user.getUserName());
    kafkaBaseConfInfo.setOperateTime(operatioinTime);
    kafkaBaseConfInfo.setKafkaParameterId(Integer.parseInt(kafkaParameterSet.getId().toString()));
    kafkaManageService.kafkaManageSava(kafkaBaseConfInfo);
    }
    return "1";
    }
    
    }catch (Exception e){
    logger.info(e.getMessage());
    }
    return"0";
    }

     

  • 3.在上传方法这样定义:
  • 注释:下边这个方法通过解压文件、重命名、重新打包,最后copy到其他机器。
  • public boolean kafkaUploadFile(KafkaParameterSet kafkaParameterSet,MultipartFile myFile,HttpSession session){
    boolean flag=false;
    try{
    
    String kafkaiPs=kafkaParameterSet.getIps();
    String[] ips=kafkaiPs.split(",");
    FileTool fileTool=new FileTool();
    String localPath= PagePathByNGINX.kafkaParameterSet+"/kafka"+kafkaParameterSet.getVersion();
    String file_type = myFile.getContentType();
    String fileName=myFile.getOriginalFilename();
    String kafka=PagePathByNGINX.kafkaParameterSet+"/kafka"+kafkaParameterSet.getVersion();
    String kafkaTar=PagePathByNGINX.kafkaParameterSet+"/kafka"+kafkaParameterSet.getVersion()+".tar.gz";
    /**连接jstorm 删除之前上传的版本**/
    LinuxUtils lu2=new LinuxUtils(PagePathByNGINX.jstormIp,22,PagePathByNGINX.jstorm,PagePathByNGINX.jstormPwd);
    lu2.execCommandBySession("rm -rf " + kafka);
    lu2.execCommandBySession("rm -rf " + kafkaTar);
    lu2.closeConnection();
    if(file_type.equals("application/x-gzip")||file_type.equals("application/octet-stream")||file_type.equals("application/x-gzip-compressed")){
    //解压上传文件
    boolean bp= fileTool.unzip("tar -zxvf", PagePathByNGINX.kafkaParameterSet+"/" + myFile.getOriginalFilename() + " -C "+PagePathByNGINX.kafkaParameterSet);
    int fi=fileName.indexOf(".tgz");
    String renameFileName=fileName.substring(0,fi);
    String localFile = PagePathByNGINX.kafkaParameterSet+"/"+renameFileName;
    //重命名上传文件
    boolean rename= fileTool.mvCmd(localFile,PagePathByNGINX.kafkaParameterSet+"/kafka"+kafkaParameterSet.getVersion());
    }else {
    //解压上传文件
    boolean bp2= fileTool.unzip("unzip", PagePathByNGINX.kafkaParameterSet+"/" + myFile.getOriginalFilename() + " -d "+PagePathByNGINX.kafkaParameterSet);
    int fi=fileName.indexOf(".zip");
    String renameFileName=fileName.substring(0,fi);
    String localFile=PagePathByNGINX.kafkaParameterSet+"/"+renameFileName;
    //重命名上传文件
    boolean rename= fileTool.mvCmd(localFile,PagePathByNGINX.kafkaParameterSet+"/kafka"+kafkaParameterSet.getVersion());
    }
    boolean ys= fileTool.executeCmds(new String[]{"cd "+PagePathByNGINX.kafkaParameterSet, "tar -zcvf kafka" + kafkaParameterSet.getVersion() + ".tar.gz"+" kafka"+kafkaParameterSet.getVersion()+"/"});
    String userName=PagePathByNGINX.kafka;
    String buildWay=" /home/"+userName;
    String buildWayAz="";
    if((kafkaParameterSet.getInstallPath().subSequence(0,1)).equals("/")){
    buildWay+=kafkaParameterSet.getInstallPath();
    buildWayAz=kafkaParameterSet.getInstallPath().replaceFirst("/","");
    }else{
    buildWay+="/"+kafkaParameterSet.getInstallPath();
    buildWayAz=kafkaParameterSet.getInstallPath();
    }
    for(int i=0;i<ips.length;i++){
    //在输入的kafka集群ip创建文件夹
    boolean mkdir=fileTool.jyIPLocalFiles(ips[i].toString(),22,PagePathByNGINX.kafka,PagePathByNGINX.kafkaPwd,"mkdir -p "+buildWay);
    if(mkdir){
    //从86上传到输入的kafka的ip地址
    boolean ut=fileTool.uploadLocalTo(ips[i].toString(),22,PagePathByNGINX.kafka,PagePathByNGINX.kafkaPwd,localPath+".tar.gz",buildWayAz);
    /*************************/
    //解压上传文件
    LinuxUtils lu=new LinuxUtils(ips[i].toString(),22,PagePathByNGINX.kafka,PagePathByNGINX.kafkaPwd);
    lu.execCommandBySession("cd "+buildWayAz+";tar -zxvf kafka"+kafkaParameterSet.getVersion()+".tar.gz");
    lu.closeConnection();
    }
    }
    }catch (Exception e){
    e.printStackTrace();
    }
    return flag;
    }

     

  • 4.备注①FileUploadUtils类 
  • public class FileUploadUtils {
    
    /**
    * 文件上传
    * 
    * @param template
    * 文件
    * @param templateFileName
    * 文件名
    * @param templateContentType
    * 文件根目录
    * @param tarFileRootPath
    *
    * @throws IOException
    */
    public boolean fileUpload(MultipartFile template,
    String templateContentType,
    String templateFileName,
    String tarFileRootPath) throws IOException {
    boolean flag = copy(template, templateFileName, tarFileRootPath);
    return flag;
    }
    
    private boolean copy(MultipartFile file, String fName, String tarFileRootPath) {
    
    boolean tag = false;
    /**
    * 存储路径
    */
    StringBuilder path = new StringBuilder();
    
    path.append(tarFileRootPath);
    path.append("/");
    
    makeDirByPath(path.toString());
    /**
    * 文件存储全路径
    */
    StringBuilder fileStorePath = new StringBuilder();
    fileStorePath.append(path);
    String filePath = fileStorePath.toString();
    filePath = filePath.replace("\\", "/");
    try {
    FileUtils.writeByteArrayToFile(new File(filePath,fName),file.getBytes());
    tag = true;
    }
    catch (IOException e) {
    e.printStackTrace();
    }
    return tag;
    }
    
    /**
    * 根据文件路径创建文件夹,可以是多级目录
    * 
    * @param filePath
    * 目录路径
    */
    public void makeDirByPath(String filePath) {
    File file = new File(filePath);
    if (!file.exists()) {
    file.mkdirs();
    }
    }
    
    public String getFileSize(long fileSize) {
    /*
    * 格式化计算结果,保留小数点两位
    */
    DecimalFormat format = (DecimalFormat) NumberFormat.getInstance();
    format.applyPattern("0.00");
    
    /*
    * 获取文件的KB
    */
    double kb = fileSize / 1024;
    if (fileSize > 0 && fileSize < 1024) {
    return format.format(kb) + " 字节";
    } else if (kb > 0 && kb < 1024) {
    return format.format(kb) + " KB";
    } else {
    return format.format(kb / 1024) + " MB";
    }
    }
    }

     

  • 5.备注②LinuxUtils类
  • public class LinuxUtils {
    private Connection con;
    private String userName; //用户名
    private String password; //密码
    private String ip; //ip
    private int port; //端口
    boolean isAuthed = false;
    
    public LinuxUtils(){}
    
    public LinuxUtils(String ip, int port ,String userName, String password){
    this.ip = ip;
    this.port = port;
    this.userName = userName;
    // this.userName = "root";
    this.password = password;
    // this.password = "123456";
    isAuthed = connection();//链接并登陆
    }
    
    public static void main(String[] args) {
    //只需要传入想要操作的ip,端口,用户名,密码,即可远程调用相关,该过程执行完后,记得关闭connection
    LinuxUtils lu1 = new LinuxUtils("192.168.237.101",22,"root","111111");
    // FileUploadUtils fileUploadUtils=new FileUploadUtils();
    
    // boolean tag =fileUploadUtils.fileUpload(myFile, myFile.getContentType(), myFile.getOriginalFilename(), "/home/cdpi");
    // lu1.execCommandBySession("cd /home/cdpi/bin/test86;tar -zxvf storm10.9.tar.gz");
    lu1.execCommandBySession("cd /root/bin/web_test;touch 124");
    lu1.closeConnection();
    
    //*********************************************************
    //不传入参数,是在本地执行命令
    //    LinuxUtils lu2 = new LinuxUtils();
    //    lu2.execCommandAtLocal("");
    }
    
     
    
    //发送本地文件到远端
    public void add2DestTable(String rootPath, String destPath){
    //远程服务器的用户名密码
    try{
    SCPClient scpClient = con.createSCPClient();
    //将本地文件上传到服务器端的目录下
    scpClient.put(rootPath, destPath);
    }catch(Exception e){
    e.printStackTrace();
    }
    }
    
    
    //远程执行命令
    public void execCommandBySession(String cmd){
    if(this.con == null){
    throw new RuntimeException("还未远程链接,请确定是否执行远程调用!****");
    }else{
    Session session = null;
    try {
    session = this.con.openSession();
    session.execCommand(cmd);
    BufferedReader brs = new BufferedReader(new InputStreamReader(new StreamGobbler(session.getStdout())));
    //这里是打印输出信息
    while(true){
    String line = brs.readLine();
    if(line==null){
    break;
    }
    System.out.println("反馈信息: "+line);
    }
    // System.out.println("执行了cmd: " + cmd);
    } catch (IOException e) {
    e.printStackTrace();
    }finally{
    if(session != null){
    session.close();
    }
    }
    }
    }
    /**
    * 判断kafka时候启动成功
    * */
    public String startKafkaJps(String comd){
    String startKafka = "";
    if(this.con == null){
    throw new RuntimeException("还未远程链接,请确定是否执行远程调用!****");
    }else{
    Session session = null;
    try {
    session = this.con.openSession();
    session.execCommand(comd);
    BufferedReader brs = new BufferedReader(new InputStreamReader(new StreamGobbler(session.getStdout())));
    while(true){
    String line = brs.readLine();
    if(line==null){
    break;
    }else if(line.indexOf("Kafka") > -1){
    startKafka = "Start-up";
    }
    }
    new StreamGobbler(session.getStderr());
    } catch (IOException e) {
    e.printStackTrace();
    }finally{
    if(session != null){
    session.close();
    }
    }
    }
    // System.out.println("反馈信息: " + killKafka);
    return startKafka;
    }
    //远程执行命令
    public void execSudoMkdir(String path, String group, String pwd){
    if(this.con == null){
    throw new RuntimeException("还未远程链接,请确定是否执行远程调用!****");
    }else{
    Session session = null;
    try {
    session = this.con.openSession();
    session.execCommand("cd /home/storm;./storm_sudo_mkdir.sh " + path + " " + group + " '" + pwd + "'");
    new StreamGobbler(session.getStdout());
    new StreamGobbler(session.getStderr());
    } catch (IOException e) {
    e.printStackTrace();
    }finally{
    if(session != null){
    session.close();
    }
    }
    }
    }
    
    //远程执行命令
    public void commandBySessionExec(String cmd){
    if(this.con == null){
    throw new RuntimeException("还未远程链接,请确定是否执行远程调用!****");
    }else{
    
    final List<Session> session = new ArrayList<Session>();
    try {
    session.add(this.con.openSession());
    session.get(0).execCommand(cmd);
    new Thread(new Runnable() {
    @Override
    public void run() {
    try{
    StreamGobbler sg = new StreamGobbler(session.get(0).getStdout());
    InputStreamReader isr = new InputStreamReader(sg);
    BufferedReader brs = new BufferedReader(isr,9000000);
    brs.close();
    isr.close();
    sg.close();
    }catch (Exception e){
    e.printStackTrace();
    }finally{
    session.add(null);
    }
    }
    }).start();
    new Thread(new Runnable() {
    @Override
    public void run() {
    try{
    StreamGobbler sg = new StreamGobbler(session.get(0).getStderr());
    InputStreamReader isr = new InputStreamReader(sg);
    BufferedReader brs = new BufferedReader(isr,9000000);
    brs.close();
    isr.close();
    sg.close();
    }catch (Exception e){
    e.printStackTrace();
    }finally{
    session.add(null);
    }
    }
    }).start();
    } catch (IOException e) {
    e.printStackTrace();
    }finally{
    while(true){
    if(session != null){
    if(session.size() > 1 && session.get(0) != null){
    session.get(0).close();
    break;
    }else{
    try {
    Thread.sleep(1000);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }
    }
    try {
    Thread.sleep(1000);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }
    }
    }
    }
    
    //远程执行命令
    public void commandBySessionExecsss(String cmd){
    if(this.con == null){
    throw new RuntimeException("还未远程链接,请确定是否执行远程调用!****");
    }else{
    Session session = null;
    try {
    session = this.con.openSession();
    session.execCommand(cmd);
    new StreamGobbler(session.getStdout());
    new StreamGobbler(session.getStderr());
    } catch (IOException e) {
    e.printStackTrace();
    }finally{
    if(session != null){
    session.close();
    }
    }
    }
    }
    //远程执行命令
    public boolean commandBySessionExecStorm(String[] cmds){
    boolean flag=false;
    if(this.con == null){
    throw new RuntimeException("还未远程链接,请确定是否执行远程调用!****");
    }else{
    Session session = null;
    try {
    session = this.con.openSession();
    String runCMD = "";
    for(String cmd: cmds){
    runCMD = runCMD + cmd + " ";
    }
    session.execCommand(runCMD);
    System.out.println("run :" + runCMD);
    InputStream is = new StreamGobbler(session.getStdout());
    BufferedReader brs = new BufferedReader(new InputStreamReader(is));
    while(true){
    String line = brs.readLine();
    if(line==null){
    break;
    }
    System.out.println(line);
    }
    
    /*
    if(session == null) System.out.println("NULLNULLNULLNULLNULLNULLNULLNULL");
    
    session.execCommand(cmd);
    System.out.println("--------------------12311111111111111111111111111111111111111111111111111");
    BufferedReader brs = new BufferedReader(new InputStreamReader(new StreamGobbler(session.getStdout())));
    System.out.println("12311111111111111111111111111111111111111111111111111");
    while(true){
    String line = brs.readLine();
    if(line==null){
    break;
    }
    System.out.println(line);
    }*/
    } catch (IOException e) {
    e.printStackTrace();
    }finally{
    if(session != null){
    session.close();
    }
    if(this.con != null){
    this.con.close();
    }
    }
    }
    return flag;
    }
    /**
    * 暂停kafka进程
    * */
    public String getKafkaPid(String comd){
    String killKafka = "";
    if(this.con == null){
    throw new RuntimeException("还未远程链接,请确定是否执行远程调用!****");
    }else{
    Session session = null;
    try {
    session = this.con.openSession();
    session.execCommand(comd);
    BufferedReader brs = new BufferedReader(new InputStreamReader(new StreamGobbler(session.getStdout())));
    while(true){
    String line = brs.readLine();
    if(line==null){
    break;
    }else if(line.indexOf("Kafka") > -1){
    killKafka = "kill -9 " + line.substring(0,line.indexOf(" "));
    }
    }
    new StreamGobbler(session.getStderr());
    } catch (IOException e) {
    e.printStackTrace();
    }finally{
    if(session != null){
    session.close();
    }
    }
    }
    // System.out.println("反馈信息: " + killKafka);
    return killKafka;
    }
    
    /**
    * 暂停storm进程
    * */
    public String killStorm(String comd){
    String killStorm = "";
    String stormId="";
    if(this.con == null){
    throw new RuntimeException("还未远程链接,请确定是否执行远程调用!****");
    }else{
    Session session = null;
    try {
    session = this.con.openSession();
    session.execCommand(comd);
    // new StreamGobbler(session.getStdout());
    BufferedReader brs = new BufferedReader(new InputStreamReader(new StreamGobbler(session.getStdout())));
    
    while(true){
    String line = brs.readLine();
    if(line==null){
    break;
    }else if(line.indexOf("nimbus") > -1){
    stormId+=" " + line.substring(0,line.indexOf(" "));
    }else if(line.indexOf("core")>-1){
    stormId+=" " + line.substring(0,line.indexOf(" "));
    }else if(line.indexOf("supervisor")>-1){
    stormId+=" " + line.substring(0,line.indexOf(" "));
    }else if(line.indexOf("logviewer")>-1){
    stormId+=" " + line.substring(0,line.indexOf(" "));
    }
    }
    new StreamGobbler(session.getStderr());
    } catch (IOException e) {
    e.printStackTrace();
    }finally{
    if(session != null){
    session.close();
    }
    }
    }
    killStorm = "kill -9 "+stormId;
    // System.out.println("反馈信息: " + killStorm);
    return killStorm;
    }
    
    
    //执行本地命令
    public boolean execCommandAtLocal(String cmd){
    
    Process exec = null;
    boolean isSuccess = false;
    try {
    exec = Runtime.getRuntime().exec(cmd);
    isSuccess = exec.waitFor() == 0?true:false;
    exec.destroy();
    } catch (IOException e1) {
    e1.printStackTrace();
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    return isSuccess;
    }
    
    
    //获取链接并注册
    private boolean connection(){
    con = new Connection(ip, port);
    boolean isAuthed = false;
    try {
    con.connect();
    isAuthed = con.authenticateWithPassword(userName, password);
    } catch (IOException e) {
    e.printStackTrace();
    }
    return isAuthed;
    }
    
    
    public void closeConnection(){
    if(this.con != null )
    this.con.close();
    }
    
    public Connection getCon() {
    return con;
    }
    
    public void setCon(Connection con) {
    this.con = con;
    }
    
    public String getIp() {
    return ip;
    }
    
    public void setIp(String ip) {
    this.ip = ip;
    }
    
    public int getPort() {
    return port;
    }
    
    public void setPort(int port) {
    this.port = port;
    }
    
    public String getUserName() {
    return userName;
    }
    
    public void setUserName(String userName) {
    this.userName = userName;
    }
    
    public String getPassword() {
    return password;
    }
    
    public void setPassword(String password) {
    this.password = password;
    }
    /***********压缩**************/
    public static boolean executeCmds(String[] cmds){
    boolean flag=false;
    File wd = new File("/bin");
    System.out.println(wd);
    Process proc = null;
    try {
    proc = Runtime.getRuntime().exec("/bin/bash", null, wd);
    } catch (IOException e) {
    e.printStackTrace();
    } if (proc != null) {
    BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
    PrintWriter out2 = new PrintWriter(new BufferedWriter(new OutputStreamWriter(proc.getOutputStream())), true);
    for(String cmd: cmds){
    out2.println(cmd);
    
    }
    // out2.println("cd /home/jstorm/bin/apache-tomcat-7.0.55/myfiles"); //执行该语句后返回上一级目录
    // //out2.println("pwd"); //打印当前目录
    // out2.println("tar -zcvf storm" + stormBaseConfInfo.getVersion() + ".tar.gz");//执行该目录下的jar文件,Linux下执行jar文件必须进入其所在的文件夹
    out2.println("exit");
    
    try {
    flag = proc.waitFor() == 0?true:false;
    
    
    in.close();
    out2.close();
    proc.destroy();
    } catch (Exception e) {
    e.printStackTrace();
    }
    }
    return flag;
    }
    
    }

     

  • 6.注释说明
  • 我这里是从前台传到服务器,经过各种解压、重命名、打包,然后再从服务器copy到其他机器。
posted @ 2015-12-03 15:03  付文杰  阅读(370)  评论(0)    收藏  举报