将图片从本地上传到服务器的过程详解

将图片从本地上传到服务器主要分为三个过程
第一,准备工作
第二,图片显示在前端页面
第三,发送给服务器
详情:
准备工作

  1. 定义一个input标签,type=file,然后让他隐藏,用一个lable标签设置它的for属性指向这个input,这样就可以通过设置lable的格式,达到文件上传的功能
<label for="fileupload" class="updata_file">点击这里上传图片</label>
<input type="file" id="fileupload" style="display: none" name="upload">
  1. 还需要定义一个img标签,用来接收上传的图片
<img src="" id="imageview" style="display: none">

让图片显示在前端界面

  1. 在Js中设置该input的change事件,原理就是将图片的盘符形式的地址换成http形式的地址,再将该地址赋值给img的src属性,并让其显示。
// 原理是把本地图片路径:"D(盘符):/image/..."转为"http://..."格式路径来进行显示图片
$("#fileupload").change(function() {
    var $file = $(this);
    var objUrl = $file[0].files[0];
    //获得一个http格式的url路径:mozilla(firefox)||webkit or chrome
    var windowURL = window.URL || window.webkitURL;
    //createObjectURL创建一个指向该参数对象(图片)的URL
    var dataURL;
    dataURL = windowURL.createObjectURL(objUrl);
    //把url给图片的src,让其显示
    $("#imageview").attr("src",dataURL);
    $('#imageview').attr("style","display:inline");
});

发送给服务器

  1. 通过form表单提交给服务器,第一需要设置formenctype="multipart/form-data",第二需要设置input的name属性,传一个参数
    <input type="file" id="fileupload" style="display: none" name="upload">
  2. 利用Struts2框架提供了接收图片的方法,需要接收三个参数。
    第一个,文件名称,就是获取发送来的文件名称。private String uploadFileName;
    第二个,是一个临时文件。private File upload;
    第三个,文件类型。private String uploadContentType;
    将图片从本地传到服务器,经历的过程就是先将图片生成一个临时文件存在C盘,然后再将这个临时文件拷贝到服务器。

调试:上传图片,打印这三个参数
在这里插入图片描述

  1. 在服务器端写代码将临时文件从C盘copy过来
    注:这里使用UUID生成的随机字符串给文件命名,避免文件名重复的情况发生
@Setter
private String uploadFileName; // 文件名称
@Setter
private File upload; // 上传文件,与form表单input发送的name名一样
@Setter
private String uploadContentType; // 文件类型

    public String AddImg() throws IOException {
       //处理上传的文件
        if(upload!=null){
            //获取文件扩展名
            int index = uploadFileName.lastIndexOf(".");
            String exName = uploadFileName.substring(index);
            //随机生成文件名
            String uuid = UUID.randomUUID().toString();
            //将生成的uuid中的"-"去掉,并拼接扩展名
            String fileName = uuid.replace("-", "") + exName;
            
            //新建服务器接受文件的目录
            String realPath = ServletActionContext.getServletContext().getRealPath("/upload");
            //路径转文件
            File file = new File(realPath);
            //如果文件不存在,新建文件夹
            if(!file.exists()){
                file.mkdirs();
            }
            //拼接新文件路径
            File newFile = new File(realPath + "/" + fileName);
            //把临时文件copy过来
            FileUtil.copyFile(upload,newFile);
        }
        return null;
    }

思路很简单:就是先获取文件的扩展名,然后生成随机的UUid,将UUid中的“-”去掉之后,拼接上扩展名就是服务器存储该图片的名称。然后在服务器下面新建一个目录upload,再利用FileUtil.copyFile()方法将临时文件copy过来

  • 14
    点赞
  • 143
    收藏
    觉得还不错? 一键收藏
  • 9
    评论
要使用Java实现SFTP文件传输,可以使用JSch库。以下是一个简单的示例代码,演示如何使用JSch实现SFTP上传文件到资源服务器: ```java import com.jcraft.jsch.*; public class SFTPUploader { public static void main(String[] args) { String host = "sftp.example.com"; String username = "your-username"; String password = "your-password"; int port = 22; String localFilePath = "/path/to/local/file.txt"; String remoteFilePath = "/path/to/remote/file.txt"; JSch jsch = new JSch(); Session session = null; try { session = jsch.getSession(username, host, port); session.setConfig("StrictHostKeyChecking", "no"); session.setPassword(password); session.connect(); ChannelSftp channelSftp = (ChannelSftp) session.openChannel("sftp"); channelSftp.connect(); channelSftp.put(localFilePath, remoteFilePath); channelSftp.disconnect(); } catch (JSchException | SftpException e) { e.printStackTrace(); } finally { if (session != null) { session.disconnect(); } } } } ``` 在这个示例代码,`host`是资源服务器的主机,`username`和`password`是SFTP登录凭据,`port`是SFTP端口,默认为22。`localFilePath`是本地文件路径,`remoteFilePath`是远程文件路径。 `JSch`实例用于创建SFTP会话,`Session`实例用于连接到资源服务器。在此示例代码,我们使用`StrictHostKeyChecking`配置来禁用主机密钥检查。接下来,我们打开一个SFTP通道,并将本地文件上传到远程服务器。 请注意,如果您需要进行多个文件传输,则应该重用单个`Session`和`ChannelSftp`实例,而不是每次传输都打开和关闭新的会话和通道。
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值