123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172 |
- package com.fdkankan.sale.service.impl;
- import com.fdkankan.fyun.face.FYunFileServiceInterface;
- import com.fdkankan.sale.common.CacheUtil;
- import com.fdkankan.sale.common.FilePath;
- import com.fdkankan.sale.common.ResultCode;
- import com.fdkankan.sale.exception.BusinessException;
- import org.apache.commons.lang3.StringUtils;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.beans.factory.annotation.Value;
- import org.springframework.stereotype.Service;
- import org.springframework.web.multipart.MultipartFile;
- import javax.annotation.Resource;
- import java.io.File;
- import java.util.UUID;
- @Service
- public class UploadService {
- @Autowired
- FYunFileServiceInterface fYunFileServiceInterface;
- public String uploadFile(MultipartFile file) {
- if(file.isEmpty()){
- throw new BusinessException(ResultCode.UPLOAD_FILE_NO_EXIST);
- }
- if(file.getSize()>10 * 1024 * 1024 * 100){
- System.out.println(file.getSize());
- throw new BusinessException(ResultCode.UPLOAD_FILE_TO_LONG);
- }
- //获取文件名
- String fileName = file.getOriginalFilename();
- if(StringUtils.isEmpty(fileName)){
- throw new BusinessException(ResultCode.UPLOAD_FILE_NO_EXIST);
- }
- File localFile = null;
- try {
- //获取文件后缀名
- String suffixName = fileName.substring(fileName.lastIndexOf("."));
- //重新生成文件名
- fileName = UUID.randomUUID().toString().replace("-","") ;
- localFile = File.createTempFile(fileName ,suffixName);
- //localFile = new File(String.format(FilePath.file_path,CacheUtil.environment,fileName +suffixName));
- if(!localFile.getParentFile().exists()){
- localFile.mkdirs();
- }
- file.transferTo(localFile);
- String ossPath = String.format(FilePath.oss_file_path,CacheUtil.environment, fileName + suffixName);
- fYunFileServiceInterface.uploadFile(localFile.getPath(),ossPath);
- return CacheUtil.host + ossPath;
- }catch (Exception e){
- e.printStackTrace();
- }finally {
- if(localFile!=null){
- localFile.delete(); //退出删除,后续需要使用文件
- }
- }
- return null;
- }
- public void deleteOssUrl(String path) {
- try {
- fYunFileServiceInterface.deleteFile(path);
- }catch (Exception e){
- e.printStackTrace();
- }
- }
- }
|