首页 > 系统相关 >spring boot+ nginx 搭建简单的文件服务器,实现上传下载

spring boot+ nginx 搭建简单的文件服务器,实现上传下载

时间:2022-12-14 18:38:17浏览次数:52  
标签:文件 String spring 上传下载 boot fileName file new log


项目中用的文件服务的上传和下载访问的问题,由于疫情没有办法接入大的分布式是文件服务器中,自己就动手搭建一个文件服务器来nginx+spring boot 。

实现的主要思路如下:

spring boot 主要实现文件的上传功能,上传到指定的目录下,这里所说的是Linux。

nginx 通过配置实现文件的浏览和下载功能。

1. sping boot 实现文件的上传代码实现如下单个文件和多个文件上传:


FileUploadController类实现如下:


@ResponseBody
@PostMapping(value = "/upload")
public BaseResponse uploadfile(@RequestParam("file") MultipartFile file){

UploadFileResp uploadFileResp = new UploadFileResp();
try {
String fileName = fileUploadService.handleFileUpload(file).getFileName();
String fileid = getFileNameNoEx(fileName);
uploadFileResp.setFileid(fileid);
fileUploadService.insertFileInfo(fileid,fileName);

log.info("uploadfile="+fileName);
} catch (Exception e) {
log.error(e.getMessage());
return BaseResponse.Exp("上传文件异常");
}

return BaseResponse.Ok().putData(uploadFileResp);
}

/**
* 多个文件上传
* @param request
* @return
*/
@ResponseBody
@PostMapping("/multiupload")
public BaseResponse multiuploadfile(HttpServletRequest request){

List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
UploadFileResp uploadFileResp = new UploadFileResp();

StringBuilder stringBuilder = new StringBuilder();
try {
for (int i = 0; i < files.size(); i++) {

MultipartFile file = files.get(i);
String fileName = fileUploadService.handleFileUpload(file).getFileName();
String fileidorg = getFileNameNoEx(fileName);
fileUploadService.insertFileInfo(fileidorg,fileName);
stringBuilder.append(fileidorg).append(",");
log.info("uploadfile=" + fileName);

}
String fileid = stringBuilder.toString();
fileid = fileid.substring(0, fileid.length() -1);
uploadFileResp.setFileid(fileid);
} catch (Exception e) {
log.error(e.getMessage());
return BaseResponse.Exp("上传文件异常");
}
return BaseResponse.Ok().putData(uploadFileResp).putTotal(files.size());
}


FileUploadService 的实现文件的上传到指定的目录如下:


// 上传的文件路径 如 /data/file/ 
@Value("${fileUpload.pathToUploadFolder:#{null}}")
public String pathToUploadFolder;

// http://www.file.com/upload/
@Value("${fileUpload.imageUrl:#{null}}")
private String fileImageUrl;

public static class FileModel {
public String getFileName() {
return fileName;
}

@JsonProperty("file_name")
public String fileName;
public FileModel(String fileName) {
this.fileName = fileName;
}
}


public FileModel handleFileUpload( MultipartFile file) throws Exception {

String name = file.getOriginalFilename();
log.info("try load image " + name);

String newPhotoName = FileUploadHelper.getUniqueName(name);
log.info("generate new unique file name " + newPhotoName);

if (file.isEmpty()) {
log.error("file " + name + " is empty");
throw new IllegalArgumentException("Uploaded file is empty");
}
// 不关心上传文件类型
//if (!FileUploadHelper.isImageContentType(file.getContentType())) {
// log.error("No supported content type " + file.getContentType());
// MediaType mediaType = MediaType.parseMediaType(file.getContentType());
// //throw Exception;
//}

String path = pathToUploadFolder + newPhotoName;

log.info("path to upload file - " + path);
try {
byte[] bytes = file.getBytes();

BufferedOutputStream stream =
new BufferedOutputStream(
new FileOutputStream(new File(path)
)
);

stream.write(bytes);
stream.close();

log.info("file successfully save by path - " + path);

return new FileModel(newPhotoName);
} catch (Exception e) {
log.debug("error save file by path " + path, e);
throw new Exception("No file was uploaded");
}
}

对文件中的名称进行uuid

public static String getUniqueName(String oldFileName) {
String extension = getFileExtension(oldFileName);
String newName = UUID.randomUUID().toString();
return newName + '.' + extension;
}

2. nignx 文件中配置如下:

http 处添加如下:

autoindex on;# 显示目录
autoindex_exact_size on;# 显示文件大小
autoindex_localtime on;# 显示文件时间

添加server 节点:

server {
listen 4040 default_server;
listen [::]:4040 default_server;
server_name _;
root /data/file/;

location / {
}

error_page 404 /404.html;
location = /40x.html {
}

error_page 500 502 503 504 /50x.html;
location = /50x.html {
}
}

到此已成了文件的上传和下载相关操作,谢谢大家斧正,谢谢。

标签:文件,String,spring,上传下载,boot,fileName,file,new,log
From: https://blog.51cto.com/u_15461374/5938150

相关文章

  • spring boot + Redis实现消息队列-生产消费者
    实现思路:Redis本身提供了一个发布/订阅模式,但生产消费者模式需要我们自己去实现。利用Redis中的队列,将新消息放入名称为xx的队列末尾,完成消息生产者。启动一个线程,使用​​b......
  • SpringBoot 设置动态定时任务
    前言SpringBoot项目中简单使用定时任务,不过由于要借助cron表达式且都提前定义好放在配置文件里,不能在项目运行中动态修改任务执行时间,不是太灵活,改文章是主要是实现在固定的......
  • spring boot 实现Mysql数据脚本导出和数据库脚本的导入
    前言在开发过程中这样一个需求,有些数据需要从数据库导出,然后导入到另外的数据库中。数据导出@SneakyThrowspublicStringexport(){//获取数据库连接对象......
  • 【Java】Spring Cache 缓存
    SpringCache一、Spring缓存抽象Spring从3.1开始定义了org.springframework.cache.Cache和org.springframework.cache.CacheManager接口来统一不同的缓存技术;并支......
  • Spring Integration的网络通量支持
    WebFluxSpring集成模块()允许以反应方式执行HTTP请求和处理入站HTTP请求。​​spring-integration-webflux​​您需要将此依赖项包含在项目中:<dependency><groupI......
  • SpringMVC学习
    SpringMVC学习1.回顾MVC1.1什么是MVCMVC是模型(Model)、视图(View)、控制器(Controller)的简写,是一种软件设计规范。是将业务逻辑、数据、显示分离的方法来组织代码......
  • spring mvc环境之异常错误码的统一返回(十五)
    1.根据不同的请求方式,返回页面或json数据1).创建统一权限异常处理类,所有的权限异常走一个端口2).根据请求方式不同返回不同数据,页面请求返回403未授权页面,ajax请......
  • spring学习-1.使用Maven构建spring项目
    1.新建一个Maven项目​​​​​​项目的结构图​​​​2.配置pom.xml,引入项目需要的依赖,这里引入了spring,junit<?xmlversion="1.0"encoding="UTF-8"?><projectxmlns......
  • Maven构建spring整合mybatis的项目
    1.使用Maven构建java项目,修改pom.xml文件,添加所需的依赖jar包<?xmlversion="1.0"encoding="UTF-8"?><projectxmlns="http://maven.apache.org/POM/4.0.0"xmlns:......
  • Spring Cloud Config介绍
    市场上的开源的配置中心有很多,如奇虎360的QConf、淘宝的Diamond、百度的Disconf、携程的Apollo都可解决上述提到的问题,同样地SpringCloud提供的配置中心则是SpringCloud......