Java 实现本地、服务器上传图片至指定文件夹以及查看

5 篇文章 0 订阅
4 篇文章 0 订阅

说明

上传图片:
- 本地: 上传至项目所在的文件夹内/images
- 服务器: 上传至jar包所在的同级目录下/images

访问图片:
- 通过/images映射文件
- http://ip:port/images/文件路径

代码

application.yml

# 图片保存路径
picture:
  upload-path: /images/

初始化图片存储的路径(服务器则上传至jar包所在的同目录下

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ResourceUtils;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.FileNotFoundException;

@Configuration
@Slf4j
public class PathConfigurer {

    @Value("${picture.upload-path}")
    public String uploadPath;

    /**
     * 初始化文件存储路径
     */
    @PostConstruct
    public void init() throws FileNotFoundException {
        // 拿到当前类路径、服务器api-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes  本地target/classes
        File path = new File(ResourceUtils.getURL("classpath:").getPath());
        if (!path.exists()) {
            // 本地正常讲是肯定存在,则不需要进入;
            // 主要是服务器上,因为是在jar包内部,因此不存在,会进入到此方法,将path指向空的File
            path = new File("");
        } else {
            path = new File(System.getProperty("user.dir"));
        }
        File upload = new File(path.getAbsolutePath() + uploadPath);
        // 本地:项目所在位置文件夹内/images/  服务器:jar包所在位置/images/
        if (!upload.exists()) {
            upload.mkdirs();
        }
        // 上面会丢失最后的/ 因此需要拼接
        String imagePath = upload.getAbsolutePath() + File.separator;

        // 赋值给图片路径保存上下文中
        PicturePathContext.setUploadPath(imagePath);
        
		log.info(">>>路径初始化成功:{}", imagePath);
    }
}

保存路径的上下文工具类

public class PicturePathContext {

    /**
     * 文件上传路径
     */
    private static String uploadPath;

    /**
     * @return {@link String} 文件路径
     */
    public static String getUploadPath() {
        return PicturePathContext.uploadPath;
    }

    /**
     * @param uploadPath 上传路径
     */
    public static void setUploadPath(String uploadPath) {
        PicturePathContext.uploadPath = uploadPath;
    }

}

资源映射配置

将/images/***的请求映射至具体的文件
@Configuration
public class ApplicationConfigurer implements WebMvcConfigurer {

    /**
     * 资源映射
     *
     * @param registry ResourceHandlerRegistry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/images/**")
                .addResourceLocations("file:" + PicturePathContext.getUploadPath());
    }

}

文件上传工具类

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.shop.common.exception.BaseException;
import com.shop.config.path.PicturePathContext;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;


public class FileUtils {

    /**
     * 上传图片
     *
     * @param files MultipartFile
     * @return {@link List}<{@link String}>
     * @throws IOException IOException
     */
    public static List<String> uploadImage(MultipartFile[] files) throws IOException {
        List<String> uploadPathList = new ArrayList<>();
        for (MultipartFile file : files) {
            if (file == null || file.isEmpty()) {
                continue;
            }
            // 文件真实名称
            String fileRealName = file.getOriginalFilename();
            assert fileRealName != null;
            // 文件后缀名 不带.
            String fileSuffix = fileRealName.substring(fileRealName.lastIndexOf("."));
            // 日期文件夹
            String folder = DateUtil.format(new Date(), "yyyyMMdd") + "/";
            // 虚拟文件名
            String fileName = IdUtil.simpleUUID();

            // 目录文件夹不存在则创建
            File dir = new File(PicturePathContext.getUploadPath() + folder);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            // 目标文件
            File dest = new File(PicturePathContext.getUploadPath() + folder + fileName + fileSuffix);
            file.transferTo(dest);

            String path = "/" + folder + fileName + fileSuffix;
            uploadPathList.add(path);
        }
        if (CollectionUtil.isEmpty(uploadPathList)) {
            throw new BaseException("图片上传失败");
        }
        return uploadPathList;
    }
}

效果

本地
请添加图片描述
请添加图片描述

请添加图片描述

服务器

模拟服务器以jar包的形式启动

请添加图片描述

请添加图片描述
请添加图片描述

实现将本地的jar包发送到服务器指定文件夹,可以使用Java中的FTP客户端库,例如Apache Commons Net或Java FTP Client。下面是使用Apache Commons Net实现将jar包发送到服务器指定文件夹的示例代码: ```java import java.io.File; import java.io.FileInputStream; import java.io.IOException; import org.apache.commons.net.ftp.FTP; import org.apache.commons.net.ftp.FTPClient; public class FtpClientExample { public static void main(String[] args) { String server = "ftp.example.com"; int port = 21; String user = "username"; String password = "password"; FTPClient ftpClient = new FTPClient(); try { ftpClient.connect(server, port); ftpClient.login(user, password); ftpClient.enterLocalPassiveMode(); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); String remoteDirPath = "/path/to/remote/dir/"; String localJarFilePath = "/path/to/local/jar/file.jar"; File localFile = new File(localJarFilePath); String remoteFileName = localFile.getName(); String remoteFilePath = remoteDirPath + remoteFileName; FileInputStream inputStream = new FileInputStream(localFile); System.out.println("Start uploading file"); boolean done = ftpClient.storeFile(remoteFilePath, inputStream); inputStream.close(); if (done) { System.out.println("The file is uploaded successfully."); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (ftpClient.isConnected()) { ftpClient.logout(); ftpClient.disconnect(); } } catch (IOException ex) { ex.printStackTrace(); } } } } ``` 这段代码通过FTP连接到服务器,设置传输模式为二进制模式,然后将本地的jar包上传到远程服务器指定文件夹中。可以根据需要修改代码实现其他FTP操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值