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

3 4

import cn.hutool.core.img.Img;
5
import cn.wisenergy.common.constant.CommonAttributes;
6
import cn.wisenergy.common.expection.BaseException;
m1991's avatar
m1991 committed
7
import cn.wisenergy.common.utils.*;
8

9
import cn.wisenergy.mapper.UsersMapper;
10
import cn.wisenergy.mapper.userLikesMapper;
11
import cn.wisenergy.model.app.*;
12
import cn.wisenergy.model.dto.ShopZxUserDto;
13
import cn.wisenergy.model.dto.ZxUserDto;
14 15
import cn.wisenergy.model.vo.ShopZxUserVo;
import com.github.pagehelper.PageInfo;
16 17 18 19 20
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;
21

22 23 24

import java.io.File;
import java.io.FileOutputStream;
25 26 27 28 29 30
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;
31

32
import cn.wisenergy.service.app.UploadService;
33

34

35
import java.util.*;
36 37
import java.util.List;

38
import javax.servlet.http.HttpServletRequest;
39

40 41 42 43
import cn.wisenergy.mapper.ShopZxMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
44

45

46

47 48 49 50 51
/**
 * Created by m1991 on 2021/2/24 13:42
 */
@Slf4j
@Transactional
licc's avatar
licc committed
52
@Service
53 54 55 56 57
public class UploadServiceImpl implements UploadService {

    @Autowired
    private ShopZxMapper shopZxMapper;

58 59 60
    @Autowired
    private UsersMapper usersMapper;

61 62 63
    @Autowired
    private userLikesMapper LikesMapper;

64
    // @Value("${file.upload.path:#{null}}")
liqin's avatar
liqin committed
65
    private String path;
m1991's avatar
m1991 committed
66 67

    /**
68
     * TODO 视频文件上传
69 70
     */
    @Override
71 72
    public Map<String, Object> uploadVideo(MultipartFile file, HttpServletRequest request, String zxField, String inviteCode) throws Exception {
        Map<String, Object> resultMap = new HashMap<String, Object>();
73
        /**
74 75
         * http://路径  request.getScheme() + "://" + request.getServerName()
         *                 + ":" + request.getServerPort()+/upload/";"
76
         */
77
        String basePath = "/upload/";
78
        Long time = System.currentTimeMillis();
79 80 81

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

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

94 95 96
        //将内存中的数据写入磁盘
        file.transferTo(newFile);
        //视频上传保存url
97
        String videoUrl = basePath + newFileName;
98 99

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

106
        resultMap.put("videoUrl", videoUrl);
107
        resultMap.put("imgUrl", imgUrl);
108
        resultMap.put("code", 0);
109 110
        resultMap.put("msg", "视频上传成功");
        String zxUrl = videoUrl;
111
        //System.out.println("上传的文件名为:"+fileName+",后缀名为:"+newFileName);
112 113 114
        /**
         * 生成当前时间戳
         */
115 116
        Long zxDate = System.currentTimeMillis();
        shopZxMapper.zxadd(zxUrl, zxField, inviteCode, zxDate);
117 118 119
        return resultMap;
    }

120
    /**
121
     * TODO 图片文件上传
122 123 124 125 126
     */
    @Override
    public Map<String, Object> uploadImage(MultipartFile file, String inviteCode) throws Exception {
        Map<String, Object> resultMap = new HashMap<String, Object>();

127
        /**
128
         * 生成当前时间戳
129
         */
130
        Long zxDate = System.currentTimeMillis();
131

132
        String basePath = "/upload/";
133

134

135
        Long time = System.currentTimeMillis();
136

137 138 139 140 141 142 143 144 145 146 147 148
        String zxName = file.getOriginalFilename();//文件原始名称
        assert zxName != null;
        String suffixName = zxName.substring(zxName.lastIndexOf("."));//从最后一个.开始截取。截取zxName的后缀名
        String newzxName = time + suffixName; //文件新名称
        //设置文件存储路径,可以存放在你想要指定的路径里面
        String rootPath = "/opt/upload/video/"; //上传图片存放位置
        String filePath = rootPath + newzxName;
        File newFile = new File(filePath);
        //判断目标文件所在目录是否存在
        if (!newFile.getParentFile().exists()) {
            //如果目标文件所在的目录不存在,则创建父目录
            newFile.getParentFile().mkdirs();
149
        }
150 151 152 153 154 155 156 157 158 159 160 161
        User user = usersMapper.InvitedCode2(inviteCode);
        String userId = user.getUserId();
        //将内存中的数据写入磁盘
        file.transferTo(newFile);
        //图片上传保存url
        String zxUrl = basePath + newzxName;
        resultMap.put("zxUrl", zxUrl);
        resultMap.put("code", 0);
        resultMap.put("msg", "头像上传成功!!!");
        // shopZxMapper.zxadd1(zxUrl,userId);
        return resultMap;
    }
162

163
    /**
164
     * TODO 多图片
165
     *
166 167 168 169 170
     * @param files
     * @param zxField
     * @param inviteCode
     * @return
     */
171
    @Override
172
    public Map imageUpload(MultipartFile[] files, String zxField, String inviteCode) {
173
        String zxUrl = new String();
174
        String xxurl=new String();
175 176
        if (null == inviteCode || "".equals(inviteCode)) {
            inviteCode = "0";
177 178
        }
        HashMap map = new HashMap();
179
        //正则去除特殊符号
180
        //String a = inviteCode.replaceAll("\"(\\b[^\"]+|\\s+)?\"(\\b[^\"]+\\b)?\"([^\"]+\\b|\\s+)?\"","\"$1$2$3\"");
181 182
        //过滤传入的邀请码带有“”的符号
        inviteCode = inviteCode.replace("\"", "").replace("\"", "");
183
        //获取上传图片数量,打印在控制台
184
        if(null!=files&&!"".equals(files)){
185 186 187 188 189 190 191 192 193 194
            System.out.println("上传图片数量" + files.length);
            //创建集合
            List<Map<String, Object>> root = new ArrayList<Map<String, Object>>();
            String fileName1 = null;

            Long time = System.currentTimeMillis();

            Map<String, Object> result = new HashMap<String, Object>();//一个文件上传的结果
            String msg = "";//上传结果信息
            //上传图片不为空时
195 196 197 198 199
//            long sa = 0;
//            for (MultipartFile file : files) {
//                sa = file.getSize();
//            }
            if (null!=files&&!"".equals(files)) {
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
                //遍历图片数据
                for (MultipartFile file : files) {

                    //判断上传文件格式
                    String fileType = file.getContentType();
                    log.info(file.getSize() + "");
                    if (("image/jpeg").equals(fileType) || ("image/png").equals(fileType) || ("image/gif").equals(fileType) || ("image/jpg").equals(fileType) || ("image/bmp").equals(fileType) || ("application/octet-stream").equals(fileType)) {
                        //上传后保存的文件名(需要防止图片重名导致的文件覆盖)
                        //获取文件名
                        fileName1 = file.getOriginalFilename();
                        String fileName;
                        //获取文件后缀名
                        try {
                            String suffixName = fileName1.substring(fileName1.lastIndexOf("."));
                            //重新生成文件名
                            fileName = "1" + UUID.randomUUID() + suffixName;//文件新名称
                        } catch (
                                Exception e
                        ) {
                            //重新生成文件名
                            fileName = "1" + UUID.randomUUID() + fileName1 + ".jpg";//文件新名称
                        }
                        //设置文件存储路径,可以存放在你想要指定的路径里面
                        String Path = "/upload/";
                        String Path1 = "/opt/upload/video/"; //上传图片存放位置
                        zxUrl += Path + fileName + ",";
                        String UrlzxPath ="/opt/upload/video/";
                        xxurl=UrlzxPath+ fileName;
                        if (FileUtils.upload(file, Path1, fileName)) {
                            //文件存放的相对路径(一般存放在数据库用于img标签的src)
                            String relativePath = "用于判断是否图片上传成功,返回值有:" + fileName;
                            result.put("relativePath", relativePath);//前端根据是否存在该字段来判断上传是否成功
                            msg = "图片上传成功";
                            result.put("zxUrl", zxUrl);
                            FileOutputStream fouts = null;
235 236 237 238 239
                            if(!("image/gif").equals(fileType)){
                                Img.from(cn.hutool.core.io.FileUtil.file(xxurl))
                                        .setQuality(0.8)//压缩比率
                                        .write(cn.hutool.core.io.FileUtil.file(xxurl));
                            }
240 241 242 243

                        } else {
                            msg = "图片上传失败";
                        }
244
                    } else {
245
                        msg = "图片格式不正确";
246
                    }
247
                }
248 249 250 251 252 253 254 255 256 257
                result.put("code", 0);
                result.put("msg", msg);
                /**
                 * 生成当前时间戳
                 */
                Long zxDate = Long.valueOf(System.currentTimeMillis());

                shopZxMapper.zxadd(zxUrl, zxField, inviteCode, zxDate);
                return result;
                //用户只上传文字时
258
        }
259

260 261

        } else if (null != zxField && files == null) {
262 263 264 265
            /**
             * 生成当前时间戳
             */
            Long zxDate = Long.valueOf(System.currentTimeMillis());
266
//            zxUrl="0";
267 268
            shopZxMapper.zxadd(zxUrl, zxField, inviteCode, zxDate);
            //图片与文字都为null的时候,给前端返回提示!
269
        } else
270
            if (null == files && null == zxField) {
271 272 273
                map.put("code", 1);
                map.put("msg", "上传资讯不能为空,请重新上传!");
                return map;
274
            }
275

276 277 278
        map.put("code", 0);
        map.put("msg", "资讯上传成功!");
        return map;
279
    }
280

281
    /**
282
     *  TODO 多文件上传
283 284 285
     */
    private Path fileStorageLocation; // 文件在本地存储的地址

liqin's avatar
liqin committed
286
    public UploadServiceImpl() {
liqin's avatar
liqin committed
287 288 289 290 291 292 293
        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);
            }
294 295 296 297 298
        }
    }

    /**
     * 存储文件到系统
299
     *
300 301 302
     * @param file 文件
     * @return 文件名
     */
licc's avatar
licc committed
303
    @Override
304 305 306 307 308
    public String storeFile(MultipartFile file) {
        // Normalize file name
        String fileName = StringUtils.cleanPath(file.getOriginalFilename());
        try {
            // Check if the file's name contains invalid characters
309
            if (fileName.contains("..")) {
310 311 312 313 314 315 316 317 318 319 320
                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
321
    @Override
322 323 324 325
    public Resource loadFileAsResource(String fileName) {
        try {
            Path filePath = this.fileStorageLocation.resolve(fileName).normalize();
            Resource resource = new UrlResource(filePath.toUri());
326
            if (resource.exists()) {
327 328 329 330
                return resource;
            } else {
                throw new FileException("File not found " + fileName);
            }
331
        } catch (MalformedURLException ex) {
332 333 334 335
            throw new FileException("File not found " + fileName, ex);
        }
    }

336
    /**
337
     * 资讯文件展示
338 339
     */
    @Override
340
    public Map selectPage(int pageNum, int pageSize, String inviteCode) {
341
        Map map = new HashMap();
342
        pageNum = pageNum - 1;
343
        List<ZxUserDto> shopZxList = shopZxMapper.selectPage(pageNum,pageSize);
344

345
        for (ZxUserDto shopZx : shopZxList) {
346

347
            String[] zxUrl = shopZx.getZxUrl().split(",");
348
            ArrayList list = new ArrayList();
349
            if (!"".equals(zxUrl)) {
350
                for (String split : zxUrl) {
351 352 353 354 355 356 357 358
                    if ("".equals(split)){

                        shopZx.setAskImgList(null);
                    }else {

                        boolean arrayList = Collections.addAll(list, split);
                        shopZx.setAskImgList(list);
                    }
359
                }
360
            }
361

362

363 364 365 366
            int likedId = shopZx.getZxid();
            if (shopZx.getUserId() == null && "" != shopZx.getUserId()) {
                map.put("code", 1);
                map.put("msg", "用户不存在!请重新开始!");
367 368
                return map;
            }
369
            shopZx.setUserId(shopZx.getUserId().replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2"));
370

371
            if (null != inviteCode && "" != inviteCode) {
372
                //用户个人邀请码查询用户数据
373 374 375 376 377
                User user = usersMapper.InvitedCode2(inviteCode);
                String userLikeId = user.getUserId();
                if (null == userLikeId) {
                    map.put("code", 1);
                    map.put("msg", "用户不存在,请重新登陆!");
378 379
                    return map;
                }
380 381 382 383 384 385 386
                userLikes d = LikesMapper.selectlikes(userLikeId, likedId);
                if (null == d) {
                    shopZx.setLikedStatus(0);
                } else {
                    shopZx.setLikedStatus(1);
                }
            }
387
        }
388

389
        map.put("data", shopZxList);
390 391
        return map;
    }
392

393
    @Override
394 395 396 397 398 399 400 401 402 403 404 405 406
    public R<PageInfo<ShopZxUserVo>> getShopZxUserList(ShopZxUserDto shopZxUserDto) {
        log.info("shop-mall[]TeamUserInfoServiceImpl[]getTeamUserInfoList[]input.param.query:" + shopZxUserDto);
        if (null == shopZxUserDto) {
            return R.error("入参不能为空!");
        }
        pageHandle(shopZxUserDto);
        Map<String, Object> map = new HashMap<>(8);

        if (!org.apache.commons.lang3.StringUtils.isBlank(shopZxUserDto.getUserId())) {
            map.put("userId", shopZxUserDto.getUserId());
        }


407

408 409 410 411 412 413 414 415 416 417 418 419
        int total = shopZxMapper.count(map);

        map.put("startNum", shopZxUserDto.getStartNum());
        map.put("endNum", shopZxUserDto.getEndNum());
        List<ShopZxUserVo> list = shopZxMapper.getShopZxList(map);
        PageInfo<ShopZxUserVo> info = new PageInfo<>();
        info.setPageSize(shopZxUserDto.getPageSize());
        info.setPageNum(shopZxUserDto.getPageNo());
        info.setList(list);
        info.setTotal(total);

        return R.ok(info);
420 421
    }

422 423


424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448
    /**
     * 分页处理方法
     *
     * @param schemeVo 参数
     */
    private void pageHandle(ShopZxUserDto schemeVo) {
        Integer pageNum = schemeVo.getPageNo();
        Integer pageSize = schemeVo.getPageSize();
        if (null == pageSize || pageSize == 0) {
            pageSize = 10;
        }
        if (null == pageNum || pageNum == 0) {
            pageNum = 1;
        }
        Integer endNum = pageSize;
        Integer startNum = (pageNum - CommonAttributes.NUM_ONE) * pageSize;
        schemeVo.setEndNum(endNum);
        schemeVo.setStartNum(startNum);
        schemeVo.setPageNo(pageNum);
        schemeVo.setPageSize(pageSize);
    }




449 450
    /**
     * 资讯点赞实现
451
     *
452
     * @param
453 454 455
     * @return
     */
    @Override
456
    public Map Ilike(Integer zxid, String inviteCode) {
457
        Map map = new HashMap();
458
        //用户个人邀请码查询用户数据
459
        User user = usersMapper.InvitedCode2(inviteCode);
460
        //用户等于null
461 462 463
        if (null == user || "".equals(user)) {
            map.put("code", 1);
            map.put("msg", "用户信息不存在,请先注册!");
464 465
            return map;
            //用户存在
466
        } else {
467
            //判断该用户是否点过赞,如果点过赞,就返回信息告知前端,
468 469 470 471
            String userLikeId = user.getUserId();
            int likedId = zxid;
            userLikes b = LikesMapper.selectlikes(userLikeId, likedId);
            if (b == null) {
472
                // 没有点过的话,就进行插入点赞记录表,更新点赞数
473 474 475 476 477 478 479 480 481 482 483 484 485 486 487
                Integer likedType = 0;//点赞类型为扩展类型,暂时默认0
                Integer likedStaus = 1; //更新点赞状态
                LikesMapper.addlikes(userLikeId, likedId, likedStaus, likedType);
                shopZx shopZx = shopZxMapper.selectByzxid(zxid);
                int a = shopZx.getZxLikes();
                Integer zxLikes = shopZx.setZxLikes(a + 1);
                shopZxMapper.updateByzxid(zxid, zxLikes);
                map.put("LikedStatus", likedStaus);
                map.put("code", 0);
                map.put("msg", "点赞成功!");
            } else {
                map.put("code", 1);
                map.put("msg", "点赞失败!");
            }
            ;
488
        }
489 490
        return map;
    }
491
    /**
492
     * 资讯审核-----1是通过 0是驳回
493
     * @param zxid
494
     * @param approval
495 496 497
     * @return
     */
    @Override
498
    public Map toExamine(Integer zxid,Integer approval) {
499 500 501
        Map map = new HashMap();
        try {
            shopZx shopZx = shopZxMapper.selectByzxid(zxid);
502
            if (null != shopZx) {
503
                Integer ZxToExamine = shopZx.setZxToExamine(approval);
504
                shopZxMapper.updateZxToExaminezxid(zxid, ZxToExamine);
505
            }
506
            map.put("code", 0);
507
            map.put("msg", "审核成功!");
508 509 510 511
        } catch (BaseException e) {
            map.put("code", 1);
            map.put("msg", "审核失败!");
        }
512

513 514
        return map;
    }
515
}