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

3 4

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

8
import cn.wisenergy.mapper.UsersMapper;
9
import cn.wisenergy.mapper.userLikesMapper;
10
import cn.wisenergy.model.app.*;
11 12 13 14 15
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;
16

17 18 19

import java.io.File;
import java.io.FileOutputStream;
20 21 22 23 24 25
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;
26

27
import cn.wisenergy.service.app.UploadService;
28

29

30
import java.util.*;
31 32
import java.util.List;

33
import javax.servlet.http.HttpServletRequest;
34

35 36 37 38
import cn.wisenergy.mapper.ShopZxMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
39

40

41

42 43 44 45 46
/**
 * Created by m1991 on 2021/2/24 13:42
 */
@Slf4j
@Transactional
licc's avatar
licc committed
47
@Service
48 49 50 51 52
public class UploadServiceImpl implements UploadService {

    @Autowired
    private ShopZxMapper shopZxMapper;

53 54 55
    @Autowired
    private UsersMapper usersMapper;

56 57 58
    @Autowired
    private userLikesMapper LikesMapper;

59
    // @Value("${file.upload.path:#{null}}")
liqin's avatar
liqin committed
60
    private String path;
m1991's avatar
m1991 committed
61 62

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

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

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

89 90 91
        //将内存中的数据写入磁盘
        file.transferTo(newFile);
        //视频上传保存url
92
        String videoUrl = basePath + newFileName;
93 94

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

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

115
    /**
116
     * TODO 图片文件上传
117 118 119 120 121
     */
    @Override
    public Map<String, Object> uploadImage(MultipartFile file, String inviteCode) throws Exception {
        Map<String, Object> resultMap = new HashMap<String, Object>();

122
        /**
123
         * 生成当前时间戳
124
         */
125
        Long zxDate = System.currentTimeMillis();
126

127
        String basePath = "/upload/";
128

129

130
        Long time = System.currentTimeMillis();
131

132 133 134 135 136 137 138 139 140 141 142 143
        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();
144
        }
145 146 147 148 149 150 151 152 153 154 155 156
        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;
    }
157

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

184
        Long time = System.currentTimeMillis();
185

186 187 188 189 190
        Map<String, Object> result = new HashMap<String, Object>();//一个文件上传的结果
        String msg = "";//上传结果信息
        //上传图片不为空时
        long sa = 0;
        for (MultipartFile file : files) {
191
            sa = file.getSize();
192 193
        }
        if (sa > 0) {
194 195
            //遍历图片数据
            for (MultipartFile file : files) {
196

197 198
                //判断上传文件格式
                String fileType = file.getContentType();
199
                log.info(file.getSize() + "");
200
                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)) {
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
                    //上传后保存的文件名(需要防止图片重名导致的文件覆盖)
                    //获取文件名
                    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";//文件新名称
                    }
                    //设置文件存储路径,可以存放在你想要指定的路径里面
217 218 219 220 221
                    String Path = "/upload/";
                    String Path1 = "/opt/upload/video/"; //上传图片存放位置
                    zxUrl += Path1 + fileName + ",";
                    String UrlzxPath ="/opt/upload/video/";
                     xxurl=UrlzxPath+ fileName;
222 223 224 225 226 227
                    if (FileUtils.upload(file, Path, fileName)) {
                        //文件存放的相对路径(一般存放在数据库用于img标签的src)
                        String relativePath = "用于判断是否图片上传成功,返回值有:" + fileName;
                        result.put("relativePath", relativePath);//前端根据是否存在该字段来判断上传是否成功
                        msg = "图片上传成功";
                        result.put("zxUrl", zxUrl);
228 229 230 231 232
                        FileOutputStream fouts = null;

                        Img.from(cn.hutool.core.io.FileUtil.file(xxurl))
                                .setQuality(0.8)//压缩比率
                                .write(cn.hutool.core.io.FileUtil.file(xxurl));
233 234 235
                    } else {
                        msg = "图片上传失败";
                    }
236
                } else {
237
                    msg = "图片格式不正确";
238
                }
239 240 241 242 243 244 245
            }
            result.put("code", 0);
            result.put("msg", msg);
            /**
             * 生成当前时间戳
             */
            Long zxDate = Long.valueOf(System.currentTimeMillis());
246

247 248 249
            shopZxMapper.zxadd(zxUrl, zxField, inviteCode, zxDate);
            return result;
            //用户只上传文字时
250
        } else if (null != zxField && sa == 0) {
251 252 253 254
            /**
             * 生成当前时间戳
             */
            Long zxDate = Long.valueOf(System.currentTimeMillis());
255
//            zxUrl="0";
256 257
            shopZxMapper.zxadd(zxUrl, zxField, inviteCode, zxDate);
            //图片与文字都为null的时候,给前端返回提示!
258 259
        } else {
            if (null == files && null == zxField) {
260 261 262
                map.put("code", 1);
                map.put("msg", "上传资讯不能为空,请重新上传!");
                return map;
263 264
            }
        }
265 266 267
        map.put("code", 0);
        map.put("msg", "资讯上传成功!");
        return map;
268
    }
269

270
    /**
271
     *  TODO 多文件上传
272 273 274
     */
    private Path fileStorageLocation; // 文件在本地存储的地址

liqin's avatar
liqin committed
275
    public UploadServiceImpl() {
liqin's avatar
liqin committed
276 277 278 279 280 281 282
        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);
            }
283 284 285 286 287
        }
    }

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

325
    /**
326
     * 资讯文件展示
327 328
     */
    @Override
329
    public Map selectPage(Integer pageNum, Integer pageSize, String inviteCode) {
330
        Map map = new HashMap();
331 332
        pageNum = pageNum - 1;
        List<zxUserDto> shopZxList = shopZxMapper.selectPage(pageNum, pageSize);
333

334
        for (zxUserDto shopZx : shopZxList) {
335
            String[] zxUrl = shopZx.getZxUrl().split(",");
336 337 338 339
            ArrayList list = new ArrayList();
            if (null != zxUrl) {
                for (String split : zxUrl) {
                    boolean arrayList = Collections.addAll(list, split);
340 341
                    shopZx.setAskImgList(list);
                }
342
            }
343

344 345 346 347
            int likedId = shopZx.getZxid();
            if (shopZx.getUserId() == null && "" != shopZx.getUserId()) {
                map.put("code", 1);
                map.put("msg", "用户不存在!请重新开始!");
348 349
                return map;
            }
350
            shopZx.setUserId(shopZx.getUserId().replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2"));
351

352
            if (null != inviteCode && "" != inviteCode) {
353
                //用户个人邀请码查询用户数据
354 355 356 357 358
                User user = usersMapper.InvitedCode2(inviteCode);
                String userLikeId = user.getUserId();
                if (null == userLikeId) {
                    map.put("code", 1);
                    map.put("msg", "用户不存在,请重新登陆!");
359 360
                    return map;
                }
361 362 363 364 365 366 367
                userLikes d = LikesMapper.selectlikes(userLikeId, likedId);
                if (null == d) {
                    shopZx.setLikedStatus(0);
                } else {
                    shopZx.setLikedStatus(1);
                }
            }
368
        }
369
        map.put("data", shopZxList);
370 371
        return map;
    }
372

373 374 375
    @Override
    public List<zxUserVo> selectAll(Integer pageNum, Integer pageSize) {

376
        return shopZxMapper.selectAll(pageNum, pageSize);
377 378
    }

379 380
    /**
     * 资讯点赞实现
381
     *
382
     * @param
383 384 385
     * @return
     */
    @Override
386
    public Map Ilike(Integer zxid, String inviteCode) {
387
        Map map = new HashMap();
388
        //用户个人邀请码查询用户数据
389
        User user = usersMapper.InvitedCode2(inviteCode);
390
        //用户等于null
391 392 393
        if (null == user || "".equals(user)) {
            map.put("code", 1);
            map.put("msg", "用户信息不存在,请先注册!");
394 395
            return map;
            //用户存在
396
        } else {
397
            //判断该用户是否点过赞,如果点过赞,就返回信息告知前端,
398 399 400 401
            String userLikeId = user.getUserId();
            int likedId = zxid;
            userLikes b = LikesMapper.selectlikes(userLikeId, likedId);
            if (b == null) {
402
                // 没有点过的话,就进行插入点赞记录表,更新点赞数
403 404 405 406 407 408 409 410 411 412 413 414 415 416 417
                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", "点赞失败!");
            }
            ;
418
        }
419 420
        return map;
    }
421

422 423
    /**
     * 资讯审核
424
     *
425 426 427 428 429 430 431 432
     * @param zxid
     * @return
     */
    @Override
    public Map toExamine(Integer zxid) {
        Map map = new HashMap();
        try {
            shopZx shopZx = shopZxMapper.selectByzxid(zxid);
433 434 435
            if (null != shopZx) {
                Integer ZxToExamine = shopZx.setZxToExamine(1);
                shopZxMapper.updateZxToExaminezxid(zxid, ZxToExamine);
436
            }
437 438 439 440 441 442 443
            map.put("code", 0);
            map.put("msg", "审核通过!");
        } catch (BaseException e) {
            map.put("code", 1);
            map.put("msg", "审核失败!");
        }
        ;
444 445
        return map;
    }
446
}