UploadServiceImpl.java 14.2 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.mapper.userLikesMapper;
8
import cn.wisenergy.model.app.User;
9
import cn.wisenergy.model.app.shopZx;
10
import cn.wisenergy.model.app.userLikes;
11
import cn.wisenergy.model.app.zxUserDto;
12 13 14 15 16
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;
17

18 19 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;
import cn.wisenergy.service.app.UploadService;
import java.io.File;
26 27 28 29 30 31
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;
32

33 34 35 36 37 38

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

    @Autowired
    private ShopZxMapper shopZxMapper;

45 46 47
    @Autowired
    private UsersMapper usersMapper;

48 49 50
    @Autowired
    private userLikesMapper LikesMapper;

51
   // @Value("${file.upload.path:#{null}}")
liqin's avatar
liqin committed
52
    private String path;
m1991's avatar
m1991 committed
53 54

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

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

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

81 82 83
        //将内存中的数据写入磁盘
        file.transferTo(newFile);
        //视频上传保存url
84
        String videoUrl = basePath + newFileName;
85 86 87 88 89 90

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

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

106 107 108 109
        /**
         * 图片文件上传
         */
        @Override
110
        public Map<String, Object> uploadImage(MultipartFile file,String inviteCode) throws Exception {
111 112
            Map<String, Object> resultMap=new HashMap<String, Object>();

113 114 115
            /**
             * 生成当前时间戳
             */
116
            Long zxDate= System.currentTimeMillis();
117

118 119 120
//            request.getScheme() + "://" + request.getServerName()
//                    + ":" + request.getServerPort()+"/upload/";
            String basePath = "/upload/";
121

122

licc's avatar
licc committed
123
            Long time = System.currentTimeMillis();
124 125

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

139 140
            User user=usersMapper.InvitedCode2(inviteCode);
            String userId=user.getUserId();
141 142 143
            //将内存中的数据写入磁盘
            file.transferTo(newFile);
            //图片上传保存url
144
            String zxUrl = basePath + newzxName;
145

146
            resultMap.put("zxUrl", zxUrl);
147 148
            resultMap.put("code", 0);
            resultMap.put("msg","头像上传成功!!!");
149
            shopZxMapper.zxadd1(zxUrl,userId);
150 151 152
            return resultMap;
        }

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

219 220 221 222 223
    /**
     * 多文件上传 TODO
     */
    private Path fileStorageLocation; // 文件在本地存储的地址

liqin's avatar
liqin committed
224
    public UploadServiceImpl() {
liqin's avatar
liqin committed
225 226 227 228 229 230 231
        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);
            }
232 233 234 235 236 237 238 239
        }
    }

    /**
     * 存储文件到系统
     * @param file 文件
     * @return 文件名
     */
licc's avatar
licc committed
240
    @Override
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
    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
259
    @Override
260 261 262 263 264 265 266 267 268 269 270 271 272 273
    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);
        }
    }

274
    /**
275
     *  资讯文件展示
276 277
     */
    @Override
278
    public Map selectPage(Integer pageNum, Integer pageSize,String inviteCode) {
279
        Map map = new HashMap();
280
        pageNum=pageNum-1;
281
        List<zxUserDto> shopZxList = shopZxMapper.selectPage(pageNum,pageSize);
282

283
        for (zxUserDto shopZx : shopZxList) {
284 285 286 287 288 289 290 291 292
            String[] zxUrl = shopZx.getZxUrl().split(",");
          ArrayList list =new ArrayList();
            if (null != zxUrl){
            for (String split:zxUrl) {

                boolean arrayList=Collections.addAll(list,split);

                    shopZx.setAskImgList(list);
                }
293
            }
294 295

            int likedId =shopZx.getZxid();
296 297 298 299 300
            if(shopZx.getUserId()==null&&""!=shopZx.getUserId()){
                map.put("code",1);
                map.put("msg","用户不存在!请重新开始!");
                return map;
            }
301
            shopZx.setUserId(shopZx.getUserId().replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2"));
302

303 304 305 306 307 308 309 310 311 312 313 314
            if(null!=inviteCode&&""!=inviteCode) {
                //用户个人邀请码查询用户数据
                User user=usersMapper.InvitedCode2(inviteCode);
                String userLikeId=user.getUserId();
                userLikes d = LikesMapper.selectlikes(userLikeId, likedId);
                if (null == d) {
                    shopZx.setLikedStatus(0);
                } else {
                    shopZx.setLikedStatus(1);
                }

            }
315

316
        }
317

318
        map.put("data",shopZxList);
319

320 321
        return map;
    }
322 323 324

    /**
     * 资讯点赞实现
325
     * @param
326 327 328
     * @return
     */
    @Override
329
    public Map Ilike(Integer zxid, String inviteCode) {
330
        Map map = new HashMap();
331 332 333 334
        //用户个人邀请码查询用户数据
        User user=usersMapper.InvitedCode2(inviteCode);

        //用户等于null
335
        if(null == user || "".equals(user)){
336 337 338 339 340 341
            map.put("code",1);
            map.put("msg","用户信息不存在,请先注册!");
            return map;
            //用户存在
        }else {
            //判断该用户是否点过赞,如果点过赞,就返回信息告知前端,
342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
            String userLikeId=user.getUserId();
            int likedId= zxid;
            userLikes b= LikesMapper.selectlikes(userLikeId, likedId);


            if(b==null){

                // 没有点过的话,就进行插入点赞记录表,更新点赞数
                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","点赞失败!");
                };

367
        }
368

369 370
        return map;
    }
371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393

    /**
     * 资讯审核
     * @param zxid
     * @return
     */
    @Override
    public Map toExamine(Integer zxid) {
        Map map = new HashMap();
        try {
            shopZx shopZx = shopZxMapper.selectByzxid(zxid);
            if(null!=shopZx){
                Integer ZxToExamine=shopZx.setZxToExamine(1);
                shopZxMapper.updateZxToExaminezxid(zxid,ZxToExamine);
            }
            map.put("code",0);
            map.put("msg","审核通过!");
        }catch ( BaseException e){
            map.put("code",1);
            map.put("msg","审核失败!");
        };
        return map;
    }
394
}