springboot上傳檔案的訪問
阿新 • • 發佈:2019-08-31
一、上傳
public @ResponseBody ApiResult<UploadResult> upload(@RequestParam("file") MultipartFile file, @RequestParam(value="appId") String appId, @RequestParam("group") String group, @RequestParam("fileName") String originFileName){ try { String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1).toLowerCase(); if(!allowUploadSuffixes.contains(suffix)){ throw new IotBaseException(9999, "不允許上傳該檔案型別"); } String fileKey = UUID.randomUUID().toString() + "."+suffix; FileSystemClient client = FileSystemClient.getClient(group); String url = client.upload(fileKey, file.getBytes(), appId); UploadFileEntity entity = new UploadFileEntity(); entity.setAppId(appId); entity.setGroupName(group); entity.setFileName(originFileName); entity.setFileUrl(url); entity.setMimeType(file.getContentType()); entity.setProvider(client.getProvider().name()); entity.setCreatedAt(new Date()); uploadFileEntityMapper.insert(entity); return new ApiResult<>(new UploadResult(url, originFileName)); } catch (Exception e) { e.printStackTrace(); throw new IotBaseException(ExceptionCode.SYSTEM_ERROR.code, "上傳失敗"); } }
二、訪問
- 在application.yml檔案中加入
spring:
resources:
static-location: classpath:/static/upload/
上面這一步好像不填也沒關係
- 建立配置
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/"