UploadServiceImpl.java 11.6 KB
Newer Older
1 2
package cn.wisenergy.service.app.impl;

3
import cn.wisenergy.common.expection.BaseException;
m1991's avatar
m1991 committed
4
import cn.wisenergy.common.utils.*;
5

6
import cn.wisenergy.mapper.UsersMapper;
7
import cn.wisenergy.model.app.shopZx;
8
import cn.wisenergy.model.app.zxUserDto;
9 10 11 12 13 14
import com.alibaba.fastjson.JSON;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
15

16 17 18 19 20 21 22 23
import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import cn.wisenergy.service.app.UploadService;
import java.io.File;
24 25 26 27 28 29
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import cn.wisenergy.mapper.ShopZxMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
30

31 32 33 34 35 36

/**
 * Created by m1991 on 2021/2/24 13:42
 */
@Slf4j
@Transactional
licc's avatar
licc committed
37
@Service
38 39 40 41 42
public class UploadServiceImpl implements UploadService {

    @Autowired
    private ShopZxMapper shopZxMapper;

43 44 45
    @Autowired
    private UsersMapper usersMapper;

46
   // @Value("${file.upload.path:#{null}}")
liqin's avatar
liqin committed
47
    private String path;
m1991's avatar
m1991 committed
48 49

    /**
50 51 52
     * 视频文件上传
     */
    @Override
53
    public Map<String, Object> uploadVideo(MultipartFile file,HttpServletRequest request,String zxField,String zxAddress,String inviteCode) throws Exception {
54
        Map<String, Object> resultMap=new HashMap<String, Object>();
55
        /**
56 57
         * http://路径  request.getScheme() + "://" + request.getServerName()
         *                 + ":" + request.getServerPort()+/upload/";"
58
         */
59
        String basePath ="/upload/";
60 61 62 63 64 65
        Long time = new Date().getTime();

        String fileName = file.getOriginalFilename();//文件原始名称
        String suffixName = fileName.substring(fileName.lastIndexOf("."));//从最后一个.开始截取。截取fileName的后缀名
        String newFileName = time+suffixName; //文件新名称
        //设置文件存储路径,可以存放在你想要指定的路径里面
66
        String rootPath="/opt/upload/video/"; //上传视频存放位置
67 68 69 70 71 72 73

        String filePath = rootPath+newFileName;
        File newFile = new File(filePath);
        //判断目标文件所在目录是否存在
        if(!newFile.getParentFile().exists()){
            //如果目标文件所在的目录不存在,则创建父目录
            newFile.getParentFile().mkdirs();
74 75
        }

76 77 78
        //将内存中的数据写入磁盘
        file.transferTo(newFile);
        //视频上传保存url
79
        String videoUrl = basePath + newFileName;
80 81 82 83 84 85

        //视频封面图处理
        String newImgName = time+".jpg";
        String framefile = rootPath + newImgName;
        String imgUrlSave = basePath+newImgName;//图片最终位置路径
        //视频截取封面图
86
        String imgUrl=FrameGrabberKit.getVedioImg(videoUrl, framefile, imgUrlSave);
87

88
        resultMap.put("videoUrl", videoUrl);
89
        resultMap.put("imgUrl", imgUrl);
90
        resultMap.put("returnCode", 0);
91
        String zxUrl=videoUrl;
92
        //System.out.println("上传的文件名为:"+fileName+",后缀名为:"+newFileName);
93 94 95
        /**
         * 生成当前时间戳
         */
96 97
        Long zxDate= System.currentTimeMillis();
        shopZxMapper.zxadd(zxUrl,zxField,zxAddress,inviteCode, zxDate);
98 99 100
        return resultMap;
    }

101 102 103 104
        /**
         * 图片文件上传
         */
        @Override
105
        public Map<String, Object> uploadImage(MultipartFile file, HttpServletRequest request,String zxField, String zxAddress,String inviteCode) throws Exception {
106 107
            Map<String, Object> resultMap=new HashMap<String, Object>();

108 109 110
            /**
             * 生成当前时间戳
             */
111
            Long zxDate= Long.valueOf(System.currentTimeMillis());
112

113 114 115
//            request.getScheme() + "://" + request.getServerName()
//                    + ":" + request.getServerPort()+"/upload/";
            String basePath = "/upload/";
116

117

licc's avatar
licc committed
118
            Long time = System.currentTimeMillis();
119 120 121 122 123

            String zxName = file.getOriginalFilename();//文件原始名称
            String suffixName = zxName.substring(zxName.lastIndexOf("."));//从最后一个.开始截取。截取zxName的后缀名
            String newzxName = time+suffixName; //文件新名称
            //设置文件存储路径,可以存放在你想要指定的路径里面
124
            String rootPath="/opt/upload/video/"; //上传图片存放位置
125 126 127 128 129 130 131 132 133 134 135
            String filePath = rootPath+newzxName;
            File newFile = new File(filePath);
            //判断目标文件所在目录是否存在
            if(!newFile.getParentFile().exists()){
                //如果目标文件所在的目录不存在,则创建父目录
                newFile.getParentFile().mkdirs();
            }

            //将内存中的数据写入磁盘
            file.transferTo(newFile);
            //图片上传保存url
136
            String zxUrl = basePath + newzxName;
137

138
            resultMap.put("zxUrl", zxUrl);
139
            resultMap.put("returnCode", 0);
140
            shopZxMapper.zxadd(zxUrl,zxField,zxAddress,inviteCode, zxDate);
141 142 143
            return resultMap;
        }

144 145 146 147 148 149 150 151
    /**
     * 多图片
     * @param files
     * @param zxField
     * @param zxAddress
     * @param inviteCode
     * @return
     */
152 153
    @Override
    public List imageUpload(MultipartFile[] files, String zxField, String zxAddress,String inviteCode) {
154 155
        //获取上传图片数量,打印在控制台
        System.out.println("上传图片数量" + files.length);
156
        String zxUrl = new String();
157 158
        //创建集合
        List<Map<String, Object>> root = new ArrayList<Map<String, Object>>();
159
        String fileName1=null;
160
        // 要上传的目标文件存放的绝对路径
161
//        final String localPath = path;
162
        Long time = new Date().getTime();
163
        String localPath = "/upload/";
164 165 166 167 168 169 170 171 172
        Map<String, Object> result = new HashMap<String, Object>();//一个文件上传的结果
        String result_msg = "";//上传结果信息
        //遍历图片数据
        for (MultipartFile file : files) {
            if (file.isEmpty()) {
                System.out.println("上传图片为空,请重新上传");
            }
            //判断上传文件格式
            String fileType = file.getContentType();
liqin's avatar
liqin committed
173
            if (fileType.equals("image/jpeg") || fileType.equals("image/png")) {
174 175
                //上传后保存的文件名(需要防止图片重名导致的文件覆盖)
                //获取文件名
176
                fileName1 = file.getOriginalFilename();
177
                //获取文件后缀名
178
                String suffixName = fileName1.substring(fileName1.lastIndexOf("."));
179
                //重新生成文件名
180
                String fileName ="1"+UUID.randomUUID()+suffixName;//文件新名称
181
                //设置文件存储路径,可以存放在你想要指定的路径里面
182
                String Path="/opt/upload/video/"; //上传图片存放位置
183
                zxUrl+=localPath+fileName+",";
184
                if (FileUtils.upload(file,Path, fileName)) {
185
                    //文件存放的相对路径(一般存放在数据库用于img标签的src)
186
                    String relativePath ="用于判断是否图片上传成功,返回值有:"+fileName;
187 188
                    result.put("relativePath", relativePath);//前端根据是否存在该字段来判断上传是否成功
                    result_msg = "图片上传成功";
189
                    result.put("zxUrl", zxUrl);
190 191 192 193 194 195 196 197 198 199 200 201
                } else {
                    result_msg = "图片上传失败";
                }
            } else {
                result_msg = "图片格式不正确";
            }
        }
        result.put("result_msg", result_msg);
        root.add(result);
        String root_json = JSON.toJSONString(root);
        System.out.println(root_json);
        result.put("returnCode", 0);
202 203 204 205
        /**
         * 生成当前时间戳
         */
        Long zxDate= Long.valueOf(System.currentTimeMillis());
206
        shopZxMapper.zxadd(zxUrl,zxField,zxAddress,inviteCode, zxDate);
207 208
        return root;
    }
209

210 211 212 213 214
    /**
     * 多文件上传 TODO
     */
    private Path fileStorageLocation; // 文件在本地存储的地址

liqin's avatar
liqin committed
215
    public UploadServiceImpl() {
liqin's avatar
liqin committed
216 217 218 219 220 221 222
        if (!StringUtil.isBlank(path)) {
            this.fileStorageLocation = Paths.get(path).toAbsolutePath().normalize();
            try {
                Files.createDirectories(this.fileStorageLocation);
            } catch (IOException e) {
                throw new FileException("Could not create the directory", e);
            }
223 224 225 226 227 228 229 230
        }
    }

    /**
     * 存储文件到系统
     * @param file 文件
     * @return 文件名
     */
licc's avatar
licc committed
231
    @Override
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249
    public String storeFile(MultipartFile file) {
        // Normalize file name
        String fileName = StringUtils.cleanPath(file.getOriginalFilename());

        try {
            // Check if the file's name contains invalid characters
            if(fileName.contains("..")) {
                throw new FileException("Sorry! Filename contains invalid path sequence " + fileName);
            }
            // Copy file to the target location (Replacing existing file with the same name)
            Path targetLocation = this.fileStorageLocation.resolve(fileName);
            Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);
            return fileName;
        } catch (IOException ex) {
            throw new FileException("Could not store file " + fileName + ". Please try again!", ex);
        }
    }

licc's avatar
licc committed
250
    @Override
251 252 253 254 255 256 257 258 259 260 261 262 263 264
    public Resource loadFileAsResource(String fileName) {
        try {
            Path filePath = this.fileStorageLocation.resolve(fileName).normalize();
            Resource resource = new UrlResource(filePath.toUri());
            if(resource.exists()) {
                return resource;
            } else {
                throw new FileException("File not found " + fileName);
            }
        } catch (MalformedURLException  ex) {
            throw new FileException("File not found " + fileName, ex);
        }
    }

265
    /**
266
     *  资讯文件展示
267 268
     */
    @Override
269 270
    public Map selectPage(Integer pageNum, Integer pageSize) {
        Map map = new HashMap();
271
        pageNum=pageNum-1;
272 273
        List<zxUserDto> shopZxList = shopZxMapper.selectPage(pageNum,pageSize);
        for (zxUserDto shopZx : shopZxList) {
274
            String zxUrl = shopZx.getZxUrl();
275 276
            ;
            shopZx.setUserId(shopZx.getUserId().replaceAll("(\\d{3})\\d{4}(\\d{4})","$1****$2"));
277
            String[] split = StringUtils.split(zxUrl, ",");
278 279 280 281 282
            if (null != split){
                List<String> strings = Arrays.asList(split);
                shopZx.setAskImgList(strings);
            }
        }
283
        map.put("data",shopZxList);
284

285 286
        return map;
    }
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308

    /**
     * 资讯点赞实现
     * @param zxid
     * @return
     */
    @Override
    public Map Ilike(Integer zxid) {
        Map map = new HashMap();
        try {
            shopZx shopZx = shopZxMapper.selectByzxid(zxid);
            int a = shopZx.getZxLikes();
            Integer zxLikes=shopZx.setZxLikes(a + 1);
            shopZxMapper.updateByzxid(zxid,zxLikes);
            map.put("code",0);
            map.put("msg","点赞成功!");
        }catch ( BaseException e){
            map.put("code",1);
            map.put("msg","点赞失败!");
        };
        return map;
    }
309
}