package com.fdkankan.fusion.controller; import com.fdkankan.common.constant.ErrorCode; import com.fdkankan.common.exception.BusinessException; import com.fdkankan.common.response.ResultData; import com.fdkankan.fusion.common.ResultCode; import com.fdkankan.fyun.oss.UploadToOssUtil; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import javax.annotation.Resource; import java.io.File; import java.util.UUID; @RestController @RequestMapping("/upload") public class UploadController { @Resource private UploadToOssUtil uploadToOssUtil; @Value("${upload.file-path}") private String filePath; @Value("${upload.query-path}") private String queryPath; @PostMapping("/file") public ResultData file(@RequestParam(required = false) MultipartFile file) throws Exception { if(file.isEmpty()){ throw new BusinessException(ResultCode.UPLOAD_FILE_NO_EXIST.code,ResultCode.UPLOAD_FILE_NO_EXIST.msg); } if(file.getSize()>10 * 1024 * 1024 * 100){ System.out.println(file.getSize()); throw new BusinessException(ResultCode.UPLOAD_FILE_TO_LONG.code,ResultCode.UPLOAD_FILE_TO_LONG.msg); } //获取文件名 String fileName = file.getOriginalFilename(); if(StringUtils.isEmpty(fileName)){ throw new BusinessException(ResultCode.UPLOAD_FILE_NO_EXIST.code,ResultCode.UPLOAD_FILE_NO_EXIST.msg); } //获取文件后缀名 String suffixName = fileName.substring(fileName.lastIndexOf(".")); //重新生成文件名 fileName = UUID.randomUUID().toString().replace("-",""); File localFile = File.createTempFile(fileName,suffixName); file.transferTo(localFile); String path = localFile.getPath(); uploadToOssUtil.upload(path,filePath + fileName + suffixName); if(!uploadToOssUtil.existKey(filePath + fileName + suffixName)){ throw new BusinessException(ResultCode.UPLOAD_ERROR.code,ResultCode.UPLOAD_ERROR.msg); } return ResultData.ok( queryPath + filePath + fileName + suffixName); } }