UploadServiceImpl.java 18.6 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 235 236 237 238 239 240 241
                //遍历图片数据
                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;

                            Img.from(cn.hutool.core.io.FileUtil.file(xxurl))
                                    .setQuality(0.8)//压缩比率
                                    .write(cn.hutool.core.io.FileUtil.file(xxurl));
                        } else {
                            msg = "图片上传失败";
                        }
242
                    } else {
243
                        msg = "图片格式不正确";
244
                    }
245
                }
246 247 248 249 250 251 252 253 254 255
                result.put("code", 0);
                result.put("msg", msg);
                /**
                 * 生成当前时间戳
                 */
                Long zxDate = Long.valueOf(System.currentTimeMillis());

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

258 259

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

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

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

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

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

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

343
        for (ZxUserDto shopZx : shopZxList) {
344

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

                        shopZx.setAskImgList(null);
                    }else {

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

360

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

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

387
        map.put("data", shopZxList);
388 389
        return map;
    }
390

391
    @Override
392 393 394 395 396 397 398 399 400 401 402 403 404
    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());
        }


405

406 407 408 409 410 411 412 413 414 415 416 417
        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);
418 419
    }

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
    /**
     * 分页处理方法
     *
     * @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);
    }




447 448
    /**
     * 资讯点赞实现
449
     *
450
     * @param
451 452 453
     * @return
     */
    @Override
454
    public Map Ilike(Integer zxid, String inviteCode) {
455
        Map map = new HashMap();
456
        //用户个人邀请码查询用户数据
457
        User user = usersMapper.InvitedCode2(inviteCode);
458
        //用户等于null
459 460 461
        if (null == user || "".equals(user)) {
            map.put("code", 1);
            map.put("msg", "用户信息不存在,请先注册!");
462 463
            return map;
            //用户存在
464
        } else {
465
            //判断该用户是否点过赞,如果点过赞,就返回信息告知前端,
466 467 468 469
            String userLikeId = user.getUserId();
            int likedId = zxid;
            userLikes b = LikesMapper.selectlikes(userLikeId, likedId);
            if (b == null) {
470
                // 没有点过的话,就进行插入点赞记录表,更新点赞数
471 472 473 474 475 476 477 478 479 480 481 482 483 484 485
                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", "点赞失败!");
            }
            ;
486
        }
487 488
        return map;
    }
489

490 491
    /**
     * 资讯审核
492
     *
493 494 495 496 497 498 499 500
     * @param zxid
     * @return
     */
    @Override
    public Map toExamine(Integer zxid) {
        Map map = new HashMap();
        try {
            shopZx shopZx = shopZxMapper.selectByzxid(zxid);
501 502 503
            if (null != shopZx) {
                Integer ZxToExamine = shopZx.setZxToExamine(1);
                shopZxMapper.updateZxToExaminezxid(zxid, ZxToExamine);
504
            }
505 506 507 508 509 510
            map.put("code", 0);
            map.put("msg", "审核通过!");
        } catch (BaseException e) {
            map.put("code", 1);
            map.put("msg", "审核失败!");
        }
511

512 513
        return map;
    }
514
}