PictureService
package me.zhengjie.tools.service; import me.zhengjie.tools.domain.Picture;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.multipart.MultipartFile; /**
* @author jie
* @date 2018-12-27
*/
@CacheConfig(cacheNames = "picture")
public interface PictureService { /**
* 上传图片
* @param file
* @param username
* @return
*/
@CacheEvict(allEntries = true)
Picture upload(MultipartFile file, String username); /**
* 根据ID查询
* @param id
* @return
*/
@Cacheable(key = "#p0")
Picture findById(Long id); /**
* 删除图片
* @param picture
*/
@CacheEvict(allEntries = true)
void delete(Picture picture);
}
package me.zhengjie.tools.service.impl; import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.common.exception.BadRequestException;
import me.zhengjie.common.utils.FileUtil;
import me.zhengjie.common.utils.ValidationUtil;
import me.zhengjie.tools.domain.Picture;
import me.zhengjie.tools.repository.PictureRepository;
import me.zhengjie.tools.service.PictureService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.util.Arrays;
import java.util.Optional; /**
* @author jie
* @date 2018-12-27
*/
@Slf4j
@Service(value = "pictureService")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class PictureServiceImpl implements PictureService { @Autowired
private PictureRepository pictureRepository; public static final String SUCCESS = "success"; public static final String CODE = "code"; public static final String MSG = "msg"; @Override
@Transactional(rollbackFor = Throwable.class)
public Picture upload(MultipartFile multipartFile, String username) {
File file = FileUtil.toFile(multipartFile);
//将参数合成一个请求
RestTemplate rest = new RestTemplate(); FileSystemResource resource = new FileSystemResource(file);
MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
param.add("smfile", resource); //设置头部,必须
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
headers.add("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36"); HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<MultiValueMap<String, Object>>(param,headers);
ResponseEntity<String> responseEntity = rest.exchange("https://sm.ms/api/upload", HttpMethod.POST, httpEntity, String.class); JSONObject jsonObject = JSONUtil.parseObj(responseEntity.getBody());
Picture picture = null;
if(!jsonObject.get(CODE).toString().equals(SUCCESS)){
throw new BadRequestException(jsonObject.get(MSG).toString());
}
//转成实体类
picture = JSON.parseObject(jsonObject.get("data").toString(), Picture.class);
picture.setSize(FileUtil.getSize(Integer.valueOf(picture.getSize())));
picture.setUsername(username);
picture.setFilename(FileUtil.getFileNameNoEx(multipartFile.getOriginalFilename())+FileUtil.getExtensionName(multipartFile.getOriginalFilename()));
pictureRepository.save(picture);
//删除临时文件
FileUtil.deleteFile(file);
return picture;
} @Override
public Picture findById(Long id) {
Optional<Picture> picture = pictureRepository.findById(id);
ValidationUtil.isNull(picture,"Picture","id",id);
return picture.get();
} @Override
@Transactional(rollbackFor = Exception.class)
public void delete(Picture picture) {
RestTemplate rest = new RestTemplate();
try {
ResponseEntity<String> str = rest.getForEntity(picture.getDelete(), String.class);
if(str.getStatusCode().is2xxSuccessful()){
pictureRepository.delete(picture);
}
//如果删除的地址出错,直接删除数据库数据
} catch(Exception e){
pictureRepository.delete(picture);
} }
}
package me.zhengjie.tools.service.query; import me.zhengjie.common.utils.PageUtil;
import me.zhengjie.tools.domain.Picture;
import me.zhengjie.tools.repository.PictureRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List; /**
* @author jie
* @date 2018-12-03
*/
@Service
@CacheConfig(cacheNames = "picture")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class PictureQueryService { @Autowired
private PictureRepository pictureRepository; /**
* 分页
*/
@Cacheable(keyGenerator = "keyGenerator")
public Object queryAll(Picture picture, Pageable pageable){
return PageUtil.toPage(pictureRepository.findAll(new Spec(picture),pageable));
} class Spec implements Specification<Picture> { private Picture picture; public Spec(Picture picture){
this.picture = picture;
} @Override
public Predicate toPredicate(Root<Picture> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder cb) { List<Predicate> list = new ArrayList<Predicate>(); if(!ObjectUtils.isEmpty(picture.getFilename())){
/**
* 模糊
*/
list.add(cb.like(root.get("filename").as(String.class),"%"+picture.getFilename()+"%"));
} Predicate[] p = new Predicate[list.size()];
return cb.and(list.toArray(p));
}
}
}
package me.zhengjie.tools.config; import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.servlet.MultipartConfigElement;
import java.io.File; /**
* @date 2018-12-28
* @author https://blog.csdn.net/llibin1024530411/article/details/79474953
*/
@Configuration
public class MultipartConfig { /**
* 文件上传临时路径
*/
@Bean
MultipartConfigElement multipartConfigElement() {
MultipartConfigFactory factory = new MultipartConfigFactory();
String location = System.getProperty("user.dir") + "/data/tmp";
File tmpFile = new File(location);
if (!tmpFile.exists()) {
tmpFile.mkdirs();
}
factory.setLocation(location);
return factory.createMultipartConfig();
}
}
package me.zhengjie.tools.domain; import lombok.Data;
import org.hibernate.annotations.CreationTimestamp;
import javax.persistence.*;
import java.io.Serializable;
import java.sql.Timestamp; /**
* sm.ms图床
*
* @author jie
* @date 2018-12-27
*/
@Data
@Entity
@Table(name = "picture")
public class Picture implements Serializable { @Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id; private String filename; private String url; private String size; private String height; private String width; /**
* delete URl
*/
@Column(name = "delete_url")
private String delete; private String username; @CreationTimestamp
private Timestamp createTime; @Override
public String toString() {
return "Picture{" +
"filename='" + filename + '\'' +
'}';
}
}
package me.zhengjie.tools.rest; import me.zhengjie.common.aop.log.Log;
import me.zhengjie.common.utils.RequestHolder;
import me.zhengjie.core.utils.JwtTokenUtil;
import me.zhengjie.tools.domain.Picture;
import me.zhengjie.tools.service.PictureService;
import me.zhengjie.tools.service.query.PictureQueryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.HashMap;
import java.util.Map; /**
* @author 郑杰
* @date 2018/09/20 14:13:32
*/
@RestController
@RequestMapping("/api")
public class PictureController { @Autowired
private PictureService pictureService; @Autowired
private PictureQueryService pictureQueryService; @Autowired
private JwtTokenUtil jwtTokenUtil; @Log(description = "查询图片")
@PreAuthorize("hasAnyRole('ADMIN','PICTURE_ALL','PICTURE_SELECT')")
@GetMapping(value = "/pictures")
public ResponseEntity getRoles(Picture resources, Pageable pageable){
return new ResponseEntity(pictureQueryService.queryAll(resources,pageable),HttpStatus.OK);
} /**
* 上传图片
* @param file
* @return
* @throws Exception
*/
@Log(description = "上传图片")
@PreAuthorize("hasAnyRole('ADMIN','PICTURE_ALL','PICTURE_UPLOAD')")
@PostMapping(value = "/pictures")
public ResponseEntity upload(@RequestParam MultipartFile file){
String userName = jwtTokenUtil.getUserName(RequestHolder.getHttpServletRequest());
Picture picture = pictureService.upload(file,userName);
Map map = new HashMap();
map.put("errno",0);
map.put("id",picture.getId());
map.put("data",new String[]{picture.getUrl()});
return new ResponseEntity(map,HttpStatus.OK);
} /**
* 删除图片
* @param id
* @return
*/
@Log(description = "删除图片")
@PreAuthorize("hasAnyRole('ADMIN','PICTURE_ALL','PICTURE_DELETE')")
@DeleteMapping(value = "/pictures/{id}")
public ResponseEntity delete(@PathVariable Long id) {
pictureService.delete(pictureService.findById(id));
return new ResponseEntity(HttpStatus.OK);
}
}
package me.zhengjie.tools.repository; import me.zhengjie.tools.domain.Picture;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor; /**
* @author jie
* @date 2018-12-27
*/
public interface PictureRepository extends JpaRepository<Picture,Long>, JpaSpecificationExecutor {
}
PictureService的更多相关文章
- springmvc的图片上传与导出显示
1.前端文件上传需要在form表单内添加enctype="multipart/form-data" ,以二进制传递: 2.web.xml文件内配置 <servlet-mapp ...
- uploadify批量上传
js: $("#uploadify").uploadify({ 'uploader':'uploadServlet', 'swf':'image/uploadify.swf', ' ...
- Nopcommerce 二次开发2 WEB
using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel.Syndica ...
- springmvc图片文件上传接口
springmvc图片文件上传 用MultipartFile文件方式传输 Controller package com.controller; import java.awt.image.Buffer ...
- fastdfs-client-java工具类封装
FastDFS是通过StorageClient来执行上传操作的 通过看源码我们知道,FastDFS有两个StorageClient工具类.
- nopCommerce 3.9 大波浪系列 之 开发支持多店的插件
一.基础介绍 nop支持多店及多语言,本篇结合NivoSlider插件介绍下如何开发支持多商城的小部件. 主要接口如下: ISettingService 接口:设置接口,可实现多店配置. (点击接口介 ...
- Nginx 搭建图片服务器
Nginx 搭建图片服务器 本章内容通过Nginx 和 FTP 搭建图片服务器.在学习本章内容前,请确保您的Linux 系统已经安装了Nginx和Vsftpd. Nginx 安装:http://www ...
- springboot上传文件 & 不配置虚拟路径访问服务器图片 & springboot配置日期的格式化方式 & Springboot配置日期转换器
1. Springboot上传文件 springboot的文件上传不用配置拦截器,其上传方法与SpringMVC一样 @RequestMapping("/uploadPicture&q ...
- SpringMvc + Jsp+ 富文本 kindeditor 进行 图片ftp上传nginx服务器 实现
一:html 原生态的附件上传 二:实现逻辑分析: 1.1.1 需求分析 Common.js 1.绑定事件 2.初始化参数 3.上传图片的url: /pic/upload 4.上图片参数名称: upl ...
随机推荐
- 201771010123汪慧和《面向对象程序设计Java》第十六周实验总结
一.理论部分 1.程序与进程的概念 ‐程序是一段静态的代码,它是应用程序执行的蓝本. ‐进程是程序的一次动态执行,它对应了从代码加载.执行至执行完毕的一个完整过程. ‐操作系统为每个进程分配一段独立的 ...
- PAT 2018 秋
A 1148 Werewolf - Simple Version 思路比较直接:模拟就行.因为需要序列号最小的两个狼人,所以以狼人为因变量进行模拟. #include <cstdio> # ...
- 基于图灵api的Python机器人
一.注册图灵机器人 先注册并登录图灵机器人官网: 点击创建机器人 复制机器人的key 二.搭建Python机器人 Python版本:3.6 注意替换第三行代码的apikey import reques ...
- Jquery输入框焦点事件及鼠表事件汇总
对于用户的输入框input,我们常常会用ajax来实现与后台的交互.输入框的内容我们可以用.val()方法获取,对于输入框内的事件,我们常用到焦点,如:input.blur.focus.... inp ...
- 18 12 18 给服务器添加logging 日志功能
Python中有个logging模块可以完成相关信息的记录,在debug时用它往往事半功倍 1. 日志级别 日志一共分成5个等级,从低到高分别是: DEBUG INFO WARNING ERROR C ...
- 字符串编码研究:Unicode
Unicode Unicode 编码系统可分为编码方式和实现方式两个层次. 1.编码方式 Unicode字符平面映射定义了所有的Unicode字符集. 2.实现方式(UTF8,UTF16) UTF-8 ...
- dp--P1439 最长公共子序列(LCS)
题目描述 给出1-n的两个排列P1和P2,求它们的最长公共子序列. 输入格式 第一行是一个数n, 接下来两行,每行为n个数,为自然数1-n的一个排列. 输出格式 一个数,即最长公共子序列的长度 找出两 ...
- HTTPS(身披SSL协议的HTTP)
参考链接: HTTP 与 HTTPS 的区别 HTTPS科普扫盲帖 HTTPS小结 HTTP 和 HTTPS 区别 HTTP是明文传输未加密,安全性差,HTTPS(HTTP + SSL)数据传输是加密 ...
- MyBatis+SpringMVC 框架搭建小结
前言:最近再写一款视频播放器的后台,踩了很多坑,在此总结. 设计顺序: 前提:搭建配置完好的Spring-MyBatis项目 1.流程分析,数据库设计(看似无用,真正做起来真的需要这个东西帮忙整理下思 ...
- 21. docker 数据通讯环境准备
一 . 环境搭建 1.编写 Vagrantfile 并创建虚拟机 并虚拟机host绑定外部 192.168.205.10:8888 # -*- mode: ruby -*- # vi: set ft= ...