项目中用的文件服务的上传和下载访问的问题,由于疫情没有办法接入大的分布式是文件服务器中,自己就动手搭建一个文件服务器来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 {
                }
        }

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

Logo

更多推荐