云计算百科
云计算领域专业知识百科平台

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

目录

    • 说明
    • 代码
    • 效果

说明

上传图片:
– 本地: 上传至项目所在的文件夹内/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包的形式启动

请添加图片描述

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

赞(0)
未经允许不得转载:网硕互联帮助中心 » Java 实现本地、服务器上传图片至指定文件夹以及查看
分享到: 更多 (0)

评论 抢沙发

评论前必须登录!