前端图片上传回显缩略图点击放大

<td>
    <label class="labClass" for="fileLable">
      <input type="button" id="btn" value="选择文件">
      <input type="file" id="fileLable" name="upload" onchange="imgRead()"  value="${news.picUrl}" accept="image/*">
    </label>
    <span id="text">请上传图片文件</span>
</td>
function imgRead() {
        var file = document.getElementById("fileLable");
        var imgDiv = document.getElementById("text");
        var basurl=file.defaultValue;
        for (var i = 0; i < file.files.length; i++) {
            var reader = new FileReader();
            var file1 = file.files[i];
            reader.readAsDataURL(file1);
            reader.onload = function (result) {
                //reader对象的result属性存储流读取的数据
                imgDiv.innerHTML = '<img width="30" height="30" src="' + reader.result + '" alt="" class="pic"/>'
            }
        }
        if (file.files.length==0 && basurl!=""){
            imgDiv.innerHTML = '<img width="30" height="30" src="' +'${pageContext.request.contextPath}/MainPageController/imgPreview.action?filePath='+ basurl + '" alt="" class="pic"/>'
        }
    }


    function imgShow(outerdiv, innerdiv, bigimg, _this){
        var src = _this.attr("src");//获取当前点击的pimg元素中的src属性
        $(bigimg).attr("src", src);//设置#bigimg元素的src属性
        /*获取当前点击图片的真实大小,并显示弹出层及大图*/
        $("<img/>").attr("src", src).load(function(){
            var windowW = $(window).width();//获取当前窗口宽度
            var windowH = $(window).height();//获取当前窗口高度
            var realWidth = this.width;//获取图片真实宽度
            var realHeight = this.height;//获取图片真实高度
            var imgWidth, imgHeight;
            var scale = 0.8;//缩放尺寸,当图片真实宽度和高度大于窗口宽度和高度时进行缩放
            if(realHeight>windowH*scale) {//判断图片高度
                imgHeight = windowH*scale;//如大于窗口高度,图片高度进行缩放
                imgWidth = imgHeight/realHeight*realWidth;//等比例缩放宽度
                if(imgWidth>windowW*scale) {//如宽度扔大于窗口宽度
                    imgWidth = windowW*scale;//再对宽度进行缩放
                }
            } else if(realWidth>windowW*scale) {//如图片高度合适,判断图片宽度
                imgWidth = windowW*scale;//如大于窗口宽度,图片宽度进行缩放
                imgHeight = imgWidth/realWidth*realHeight;//等比例缩放高度
            } else {//如果图片真实高度和宽度都符合要求,高宽不变
                imgWidth = realWidth;
                imgHeight = realHeight;
            }
            $(bigimg).css("width",imgWidth);//以最终的宽度对图片缩放
            var w = (windowW-imgWidth)/2;//计算图片与窗口左边距
            var h = (windowH-imgHeight)/2;//计算图片与窗口上边距
            $(innerdiv).css({"top":h, "left":w});//设置#innerdiv的top和left属性
            $(outerdiv).fadeIn("fast");//淡入显示#outerdiv及.pimg
        });
        $(outerdiv).click(function(){//再次点击淡出消失弹出层
            $(this).fadeOut("fast");
        });
    }
@RequestMapping(value = "/imgPreview")
    @ResponseBody
    public void imgPreview(String filePath,HttpServletRequest request, HttpServletResponse response){
        try {
            String theFileName=filePath.substring(filePath.lastIndexOf("/")+1, filePath.length());
            FtpUtils.sshSftpDown(null,theFileName,filePath,response);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
package com.kdgcsoft.power.common.util;

import com.jcraft.jsch.*;

import java.io.*;
import java.lang.reflect.Field;
import java.util.Properties;
import java.util.Vector;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;

/**
 * Created by shywang on 2021-08-09 17:44
 */
public class FtpUtils {
    private static String ip;
    //用户名
    private static String user;
    //密码
    private static String password;
    //服务器端口 默认22
    private static int port;
    //上传文件到指定服务器的指定目录 自行修改
    private static String path;

    /**
     * 利用JSch包实现SFTP上传文件
     *
     * @param bytes    文件字节流
     * @param fileName 文件名
     * @throws Exception
     */
    public static void sshSftp(byte[] bytes, String fileName) throws Exception {
        Properties properties = new Properties();
        ClassLoader classLoader = JdbcUtil.class.getClassLoader();
        InputStream is = classLoader.getResourceAsStream("config-development.properties");
        try {
            properties.load(is);
            ip = properties.getProperty("sftp.ip");
            user = properties.getProperty("sftp.user");
            password = properties.getProperty("sftp.password");
            port = Integer.valueOf(properties.getProperty("sftp.port"));
            path = properties.getProperty("urlPath") + "/file";
        } catch (Exception e) {
            e.printStackTrace();
        }

        Session session = null;
        Channel channel = null;
        JSch jsch = new JSch();

        if (port <= 0) {
//连接服务器,采用默认端口
            session = jsch.getSession(user, ip);
        } else {
//采用指定的端口连接服务器
            session = jsch.getSession(user, ip, port);
        }

//如果服务器连接不上,则抛出异常
        if (session == null) {
            throw new Exception("session is null");
        }

//设置登陆主机的密码
        session.setPassword(password);//设置密码
//设置第一次登陆的时候提示,可选值:(ask | yes | no)
        session.setConfig("StrictHostKeyChecking", "no");
//设置登陆超时时间
        session.connect(30000);
        OutputStream outstream = null;
        try {
//创建sftp通信通道
            channel = (Channel) session.openChannel("sftp");
            channel.connect(30000);
            ChannelSftp sftp = (ChannelSftp) channel;
            Class<ChannelSftp> c = ChannelSftp.class;
            Field f = c.getDeclaredField("server_version");
            f.setAccessible(true);
            f.set(sftp, 2);
            sftp.setFilenameEncoding("gbk");

//进入服务器指定的文件夹
            sftp.cd(path);

//列出服务器指定的文件列表
// Vector v = sftp.ls("*");
// for(int i=0;i<v.size();i++){
// System.out.println(v.get(i));
// }

//以下代码实现从本地上传一个文件到服务器,如果要实现下载,对换以下流就可以了
            outstream = sftp.put(fileName);
            outstream.write(bytes);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
//关流操作
            if (outstream != null) {
                outstream.flush();
                outstream.close();
            }
            if (session != null) {
                session.disconnect();
            }
            if (channel != null) {
                channel.disconnect();
            }
        }
    }

    //下载文件
    public static void sshSftpDown(String src, String origalName, String filePath, HttpServletResponse response) throws Exception {
        Properties properties = new Properties();
        ClassLoader classLoader = JdbcUtil.class.getClassLoader();
        InputStream is = classLoader.getResourceAsStream("config-development.properties");
        try {
            properties.load(is);
            ip = properties.getProperty("sftp.ip");
            user = properties.getProperty("sftp.user");
            password = properties.getProperty("sftp.password");
            port = Integer.valueOf(properties.getProperty("sftp.port"));
            path = properties.getProperty("urlPath") + "/file";
        } catch (Exception e) {
            e.printStackTrace();
        }

        //指定的服务器地址
        Session session = null;
        Channel channel = null;
        JSch jsch = new JSch();
        if (port <= 0) {
            //连接服务器,采用默认端口
            session = jsch.getSession(user, ip);
        } else {
            //采用指定的端口连接服务器
            session = jsch.getSession(user, ip, port);
        }
        //如果服务器连接不上,则抛出异常
        if (session == null) {
            throw new Exception("session is null");
        }
        //设置登陆主机的密码
        session.setPassword(password);//设置密码
        //设置第一次登陆的时候提示,可选值:(ask | yes | no)
        session.setConfig("StrictHostKeyChecking", "no");
        //设置登陆超时时间
        session.connect(30000);

        InputStream io = null;
        try {
            //创建sftp通信通道
            channel = (Channel) session.openChannel("sftp");
            channel.connect(30000);
            ChannelSftp sftp = (ChannelSftp) channel;
            Class<ChannelSftp> c = ChannelSftp.class;
            Field f = c.getDeclaredField("server_version");
            f.setAccessible(true);
            f.set(sftp, 2);
            sftp.setFilenameEncoding("gbk");
            String theFileName = "";//从fileName截取不含路径的文件名
            //进入服务器指定的文件夹
            if (StringUtils.isNotEmpty(src)) {
                path = src;
            } else {
                //截取路径中的文件名
                theFileName = filePath.substring(filePath.lastIndexOf("/") + 1, filePath.length());
            }
            //附件所在文件夹
            String fpath = filePath.substring(0, filePath.lastIndexOf("/"));
            sftp.cd(fpath);
            io = sftp.get(theFileName);
            String downfileName = java.net.URLEncoder.encode(origalName, "UTF-8");
            response.setContentType("MediaType.APPLICATION_OCTET_STREAM;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + downfileName);
            ServletOutputStream servletOutputStream = null;
            try {
                servletOutputStream = response.getOutputStream();
                IOUtils.copy(io, servletOutputStream);
            } finally {
                try {
                    if (servletOutputStream != null) {
                        servletOutputStream.flush();
                        servletOutputStream.close();
                    }
                } finally {
                    if (io != null) {
                        io.close();
                    }
                }
            }
    
    
     /*FileOutputStream fos = new FileOutputStream("D:/b3.doc");
     byte[] b = new byte[1024];
     while ((io.read(b)) != -1) {
         fos.write(b);// 写入数据
     }
     io.close();
     fos.close();// 保存数据
*/
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //关流操作
            if (io != null) {
                io.close();
            }
            if (session != null) {
                session.disconnect();
            }
            if (channel != null) {
                channel.disconnect();
            }
        }
    }


    //下载文件
    public static InputStream sshSftpGetIns(String src, String filePath) throws Exception {
        Properties properties = new Properties();
        ClassLoader classLoader = JdbcUtil.class.getClassLoader();
        InputStream is = classLoader.getResourceAsStream("config-development.properties");
        try {
            properties.load(is);
            ip = properties.getProperty("sftp.ip");
            user = properties.getProperty("sftp.user");
            password = properties.getProperty("sftp.password");
            port = Integer.valueOf(properties.getProperty("sftp.port"));
            path = properties.getProperty("urlPath") + "/file";
        } catch (Exception e) {
            e.printStackTrace();
        }

        //指定的服务器地址
        Session session = null;
        Channel channel = null;
        JSch jsch = new JSch();
        if (port <= 0) {
            //连接服务器,采用默认端口
            session = jsch.getSession(user, ip);
        } else {
            //采用指定的端口连接服务器
            session = jsch.getSession(user, ip, port);
        }
        //如果服务器连接不上,则抛出异常
        if (session == null) {
            throw new Exception("session is null");
        }
        //设置登陆主机的密码
        session.setPassword(password);//设置密码
        //设置第一次登陆的时候提示,可选值:(ask | yes | no)
        session.setConfig("StrictHostKeyChecking", "no");
        //设置登陆超时时间
        session.connect(30000);

        InputStream io = null;
        try {
            //创建sftp通信通道
            channel = (Channel) session.openChannel("sftp");
            channel.connect(30000);
            ChannelSftp sftp = (ChannelSftp) channel;
            Class<ChannelSftp> c = ChannelSftp.class;
            Field f = c.getDeclaredField("server_version");
            f.setAccessible(true);
            f.set(sftp, 2);
            sftp.setFilenameEncoding("gbk");
            String theFileName = "";//从fileName截取不含路径的文件名
            //进入服务器指定的文件夹
            if (StringUtils.isNotEmpty(src)) {
                path = src;
            } else {
                //截取路径中的文件名
                theFileName = filePath.substring(filePath.lastIndexOf("/") + 1, filePath.length());
            }
            //附件所在文件夹
            String fpath = filePath.substring(0, filePath.lastIndexOf("/"));
            sftp.cd(fpath);
            io = sftp.get(theFileName);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (session != null) {
                session.disconnect();
            }
            if (channel != null) {
                channel.disconnect();
            }
        }
        return io;
    }




}

 

posted on 2022-01-18 15:09  ALWAYS☆REMIND  阅读(347)  评论(0编辑  收藏  举报

导航