昨天发现用NodeJS
写的文件上传服务有严重的内存泄漏问题 …
application.yml
在application.yml
的根节点添加以下内容:
my-config: upload-real-path: /Users/net.cctv3.i/Desktop upload-cdn-path: https://cloud.cctv3.net/ environment: Development
|
MyConfig.java
构造实体类,这里变量会自动陀峰式命名,注入进去。
import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component;
@Component @Data @ConfigurationProperties(prefix = "my-config") public class MyConfig { private String uploadRealPath; private String uploadCdnPath; private String environment; }
|
使用
使用前先注入,
@Autowired MyConfig myConfig;
|
我用配置写了一个文件上传服务,不同的环境,对应不同的物理路径。
package net.cctv3.chnqoodiaryservice.controller;
import net.cctv3.chnqoodiaryservice.config.MyConfig; import org.apache.commons.io.IOUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.HashMap; import java.util.UUID;
@RestController public class FileUploaderAction { @Autowired MyConfig myConfig;
@CrossOrigin @PostMapping("/fileUploader.action") public HashMap<String, Object> fileUploaderAction(@RequestParam MultipartFile file, HttpServletRequest request) { String idQoo = request.getParameter("idQoo"); String originalFilename = file.getOriginalFilename(); HashMap<String, Object> map = new HashMap<>(); String fileExtension = originalFilename.substring(originalFilename.lastIndexOf(".")); File dir = new File(String.format("%s/%s", myConfig.getUploadRealPath(), idQoo)); if (!dir.exists()) { dir.mkdir(); } String id = UUID.randomUUID().toString(); try { File fileCache = new File(dir.getAbsolutePath(), String.format("%s%s", id, fileExtension)); if (!fileCache.exists()) { fileCache.createNewFile(); } fileCache.createNewFile(); FileOutputStream fos = new FileOutputStream(fileCache); IOUtils.copy(file.getInputStream(), fos); fos.flush(); fos.close(); map.put("success", true); map.put("data", String.format("%s/%s/%s/%s%s", myConfig.getUploadCdnPath(),myConfig.getEnvironment(), idQoo, id, fileExtension)); } catch (IOException e) { e.printStackTrace(); } return map; } }
|