Browse Source

文件上传服务

LiTaohong 6 years ago
parent
commit
4f06e1856b

+ 8 - 0
business/base-service/pom.xml

@ -62,6 +62,14 @@
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
        </dependency>
        <dependency>
            <groupId>com.yihu.jw</groupId>
            <artifactId>common-rest-model</artifactId>
        </dependency>
        <dependency>
            <groupId>com.yihu</groupId>
            <artifactId>fastdfs-starter</artifactId>
        </dependency>
        <!--   poi xml导入导出工具 end -->
    </dependencies>
</project>

+ 181 - 0
business/base-service/src/main/java/com/yihu/jw/file_upload/FileUploadService.java

@ -0,0 +1,181 @@
package com.yihu.jw.file_upload;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.yihu.fastdfs.FastDFSUtil;
import com.yihu.jw.exception.code.BaseErrorCode;
import com.yihu.jw.patient.util.ConstantUtils;
import com.yihu.jw.restmodel.iot.common.UploadVO;
import com.yihu.jw.restmodel.web.ObjEnvelop;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.net.URLDecoder;
import java.util.Base64;
/**
 * 文件上传服务
 */
@Service
public class FileUploadService {
    @Autowired
    private FastDFSUtil fastDFSHelper;
    @Value("${fastDFS.fastdfs_file_url}")
    private String fastdfs_file_url;
//    @Autowired
//    private ErrorCodeUtil errorCodeUtil;
    /**
     * 文件流上传图片
     * @param inputStream
     * @param originalFileName
     * @return
     * @throws Exception
     */
    public JSONObject uploadImg(InputStream inputStream, String originalFileName,long fileSize) throws Exception{
        JSONObject result = new JSONObject();
        // 得到文件的完整名称  xxx.txt
        if(StringUtils.isBlank(originalFileName) || null == inputStream){
            result.put("msg","图片文件名或图片文件流不可为空!");
            result.put("response", ConstantUtils.FAIL);
            return result;
        }
        //得到文件类型
        String fileType = originalFileName.substring(originalFileName.lastIndexOf(".") + 1).toLowerCase();
        if(StringUtils.isBlank(fileType)||!"jpg,jpeg,png".contains(fileType)){
            result.put("msg","图片文件格式不正确,请上传jpg,jpeg,png等任一格式!");
            result.put("response", ConstantUtils.FAIL);
            return result;
        }
        long max = 5*1024*1024;
        if(fileSize > max){
            result.put("msg","图片文件过大,请不要超过5M!");
            result.put("response", ConstantUtils.FAIL);
            return result;
        }
        String fileName = originalFileName.substring(0, originalFileName.lastIndexOf("."));
        //上传到fastdfs
        ObjectNode objectNode = fastDFSHelper.upload(inputStream, fileType, "");
        //解析返回的objectNode
        UploadVO uploadVO = new UploadVO();
        uploadVO.setFileName(fileName);
        uploadVO.setFileType(fileType);
        uploadVO.setFullUri(objectNode.get("fileId").toString().replaceAll("\"", ""));
        uploadVO.setFullUrl(fastdfs_file_url + objectNode.get("fileId").toString().replaceAll("\"", ""));
        result.put("response", ConstantUtils.SUCCESS);
        return result;
    }
/*
    *//**
     * 文件流上传附件
     * @param file
     * @return
     * @throws Exception
     *//*
    public ObjEnvelop<UploadVO> uploadAttachment(MultipartFile file) throws Exception{
        // 得到文件的完整名称  xxx.txt
        String fullName = file.getOriginalFilename();
        if(StringUtils.isBlank(fullName)){
            return failed(errorCodeUtil.getErrorMsg(BaseErrorCode.FileUpload.FAIL_UPLOAD_FORMAT), ObjEnvelop.class);
        }
        //得到文件类型
        String fileType = fullName.substring(fullName.lastIndexOf(".") + 1).toLowerCase();
        if(StringUtils.isBlank(fileType)||!"doc、docx、pdf、xls、xlsx、jpg、jpeg、png".contains(fileType)){
            return failed(errorCodeUtil.getErrorMsg(BaseErrorCode.FileUpload.FAIL_UPLOAD_FORMAT), ObjEnvelop.class);
        }
        long size = file.getSize();
        long max = 5*1024*1024;
        if(size>max){
            String msg = String.format(BaseErrorCode.FileUpload.FAIL_FILE_SIZE, 5);
            return failed(msg, ObjEnvelop.class);
        }
        String fileName = fullName.substring(0, fullName.lastIndexOf("."));
        //上传到fastdfs
        ObjectNode objectNode = fastDFSHelper.upload(file.getInputStream(), fileType, "");
        //解析返回的objectNode
        UploadVO uploadVO = new UploadVO();
        uploadVO.setFileName(fileName);
        uploadVO.setFileType(fileType);
        uploadVO.setFullUri(objectNode.get("fileId").toString().replaceAll("\"", ""));
        uploadVO.setFullUrl(fastdfs_file_url + objectNode.get("fileId").toString().replaceAll("\"", ""));
        return success("上传成功", uploadVO);
    }
    *//**
     * 文件流上传文件
     * @param file
     * @return
     * @throws Exception
     *//*
    public ObjEnvelop<UploadVO> uploadStream(@ApiParam(value = "文件", required = true)
                                             @RequestParam(value = "file", required = true) MultipartFile file) throws Exception{
        // 得到文件的完整名称  xxx.txt
        String fullName = file.getOriginalFilename();
        //得到文件类型
        String fileType = fullName.substring(fullName.lastIndexOf(".") + 1).toLowerCase();
        String fileName = fullName.substring(0, fullName.lastIndexOf("."));
        //上传到fastdfs
        ObjectNode objectNode = fastDFSHelper.upload(file.getInputStream(), fileType, "");
        //解析返回的objectNode
        UploadVO uploadVO = new UploadVO();
        uploadVO.setFileName(fileName);
        uploadVO.setFileType(fileType);
        uploadVO.setFullUri(objectNode.get("fileId").toString().replaceAll("\"", ""));
        uploadVO.setFullUrl(fastdfs_file_url + objectNode.get("fileId").toString().replaceAll("\"", ""));
        return success("上传成功", uploadVO);
    }
    *//**
     * base64上传图片
     * @param jsonData
     * @return
     * @throws Exception
     *//*
    public ObjEnvelop<UploadVO> uploadImages(@ApiParam(name = "jsonData", value = "头像转化后的输入流")
                                             @RequestBody String jsonData) throws Exception {
        if(jsonData == null){
            return failed(errorCodeUtil.getErrorMsg(BaseErrorCode.FileUpload.FILE_NULL), ObjEnvelop.class);
        }
        String date = URLDecoder.decode(jsonData,"UTF-8");
        String[] fileStreams = date.split(",");
        String is = URLDecoder.decode(fileStreams[1],"UTF-8").replace(" ","+");
        byte[] in = Base64.getDecoder().decode(is);
        String pictureName = fileStreams[0].substring(0,fileStreams[0].length()-1);
        String fileExtension = pictureName.substring(pictureName.lastIndexOf(".") + 1).toLowerCase();
        String description = null;
        if ((pictureName != null) && (pictureName.length() > 0)) {
            int dot = pictureName.lastIndexOf('.');
            if ((dot > -1) && (dot < (pictureName.length()))) {
                description = pictureName.substring(0, dot);
            }
        }
        InputStream inputStream = new ByteArrayInputStream(in);
        ObjectNode objectNode = fastDFSHelper.upload(inputStream, "png", "");
        String groupName = objectNode.get("groupName").toString();
        String remoteFileName = objectNode.get("remoteFileName").toString();
        //解析返回的objectNode
        UploadVO uploadVO = new UploadVO();
        uploadVO.setFileName(remoteFileName);
        uploadVO.setFileType(groupName);
        uploadVO.setFullUri(objectNode.get("fileId").toString().replaceAll("\"", ""));
        uploadVO.setFullUrl(fastdfs_file_url + objectNode.get("fileId").toString().replaceAll("\"", ""));
        //返回文件路径
        return success("上传成功", uploadVO);
    }*/
}

+ 0 - 8
business/base-service/src/main/java/com/yihu/jw/patient/service/BasePatientService.java

@ -115,13 +115,6 @@ public class BasePatientService extends BaseJpaService<BasePatientDO, BasePatien
            return ConstantUtils.FAIL;
        }
        BasePatientDO basePatientDO = objectMapper.readValue(patient.toJSONString(),BasePatientDO.class);
        basePatientDO.setSalt(randomString(5));
        String password = basePatientDO.getPassword();
        if (org.springframework.util.StringUtils.isEmpty(password)) {
            password = basePatientDO.getIdcard().substring(0, 5);
        }
        basePatientDO.setPassword(MD5.md5Hex(password + "{" + basePatientDO.getSalt() + "}"));
        this.save(basePatientDO);
        List<PatientMedicareCardDO> list = new ArrayList<>();
@ -178,5 +171,4 @@ public class BasePatientService extends BaseJpaService<BasePatientDO, BasePatien
        }
        return ConstantUtils.SUCCESS;
    }
}

+ 3 - 0
business/sms-service/src/main/java/com/yihu/jw/sms/dao/BaseSmsDao.java

@ -4,10 +4,13 @@ import com.yihu.jw.entity.base.sms.SmsDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.Date;
/**
 * Dao - 短信记录
 * Created by progr1mmer on 2018/8/23.
 */
public interface BaseSmsDao extends PagingAndSortingRepository<SmsDO, String>, JpaSpecificationExecutor<SmsDO> {
    boolean existsByCaptchaAndDeadlineBefore(String captcha, Date now);
}

+ 14 - 0
business/sms-service/src/main/java/com/yihu/jw/sms/service/BaseSmsService.java

@ -3,8 +3,11 @@ package com.yihu.jw.sms.service;
import com.yihu.jw.entity.base.sms.SmsDO;
import com.yihu.jw.sms.dao.BaseSmsDao;
import com.yihu.mysql.query.BaseJpaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
/**
 * Service - 短信记录
 * Created by progr1mmer on 2018/9/6.
@ -12,4 +15,15 @@ import org.springframework.stereotype.Service;
@Service
public class BaseSmsService extends BaseJpaService<SmsDO, BaseSmsDao>{
    @Autowired
    private BaseSmsDao baseSmsDao;
    /**
     * 判断验证码是否正确
     * @param captcha
     * @return
     */
    public Boolean verifyCaptcha(String captcha){
        return baseSmsDao.existsByCaptchaAndDeadlineBefore(captcha,new Date());
    }
}

+ 3 - 1
common/common-entity/src/main/java/com/yihu/jw/entity/base/sms/SmsTemplateDO.java

@ -19,11 +19,13 @@ public class SmsTemplateDO extends UuidIdentityEntityWithOperator {
     * 0 - 注册
     * 1 - 登陆
     * 2 - 重置密码
     * 3 - 修改手机号
     */
    public enum Type {
        register,
        login,
        resetPassword
        resetPassword,
        updateMobile
    }
    //应用ID

+ 1 - 0
common/common-request-mapping/src/main/java/com/yihu/jw/rm/base/BaseRequestMapping.java

@ -465,6 +465,7 @@ public class BaseRequestMapping {
        public static final String PREFIX  = "/basePatient";
        public static final String getPatientById  = "/getPatientById";
        public static final String getBaseInfo  = "/getBaseInfo";
        public static final String sendCaptcha  = "/sendCaptcha";
    }
   /**

+ 6 - 0
svr/svr-patient/pom.xml

@ -185,6 +185,12 @@
            <artifactId>base-service</artifactId>
            <version>2.0.0</version>
        </dependency>
        <dependency>
            <groupId>com.yihu.jw</groupId>
            <artifactId>sms-service</artifactId>
            <version>2.0.0</version>
            <scope>compile</scope>
        </dependency>
    </dependencies>

+ 25 - 0
svr/svr-patient/src/main/java/com/yihu/jw/patient/endpoint/personal_info/PatientEndpoint.java

@ -1,19 +1,26 @@
package com.yihu.jw.patient.endpoint.personal_info;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.base.sms.SmsDO;
import com.yihu.jw.entity.base.sms.SmsTemplateDO;
import com.yihu.jw.patient.service.personal_Info.PatientService;
import com.yihu.jw.patient.util.ConstantUtils;
import com.yihu.jw.restmodel.base.patient.BasePatientVO;
import com.yihu.jw.restmodel.base.sms.SmsVO;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.ListEnvelop;
import com.yihu.jw.restmodel.web.ObjEnvelop;
import com.yihu.jw.restmodel.web.PageEnvelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.rm.base.BaseRequestMapping;
import com.yihu.jw.sms.service.BaseSmsGatewayService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@ -37,6 +44,12 @@ public class PatientEndpoint extends EnvelopRestEndpoint {
    @Autowired
    private PatientService patientService;
    @Value("sms.clientId")
    private String clientId;
    @Autowired
    private BaseSmsGatewayService baseSmsGatewayService;
    @PostMapping(value = BaseRequestMapping.BasePatient.CREATE)
    @ApiOperation(value = "创建")
    public Envelop create(
@ -125,4 +138,16 @@ public class PatientEndpoint extends EnvelopRestEndpoint {
        List<Map<String,Object>> basePatients = patientService.queryPatientBaseInfo(nameOrIdcard, page,size,sorts);
        return success(basePatients);
    }
    @GetMapping(value = BaseRequestMapping.BasePatient.sendCaptcha)
    @ApiOperation(value = "发送验证码")
    public ObjEnvelop<SmsVO> sendCaptcha(
            @ApiParam(name = "mobile", value = "手机号")
            @RequestParam(value = "mobile", required = true) String mobile,
            @ApiParam(name = "type", value = "短信验证码类型", required = true)
            @RequestParam(value = "type") SmsTemplateDO.Type type) throws Exception {
        SmsDO smsDO = baseSmsGatewayService.send(clientId, type,mobile);
        return success(smsDO, SmsVO.class);
    }
}

+ 94 - 0
svr/svr-patient/src/main/java/com/yihu/jw/patient/service/personal_Info/PatientService.java

@ -1,6 +1,18 @@
package com.yihu.jw.patient.service.personal_Info;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.base.sms.SmsTemplateDO;
import com.yihu.jw.patient.dao.personal_info.BasePatientDao;
import com.yihu.jw.patient.service.BasePatientService;
import com.yihu.jw.patient.util.ConstantUtils;
import com.yihu.jw.sms.service.BaseSmsGatewayService;
import com.yihu.jw.sms.service.BaseSmsService;
import com.yihu.jw.sms.service.BaseSmsTemplateService;
import com.yihu.utils.security.MD5;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
/**
@ -10,4 +22,86 @@ import org.springframework.stereotype.Service;
@Service
public class PatientService extends BasePatientService {
    @Autowired
    private BasePatientDao basePatientDao;
    @Autowired
    private BaseSmsService baseSmsService;
    /**
     * 设置登录密码
     * @param id
     * @param password
     */
    public JSONObject setPassword(String id, String password){
        JSONObject result = new JSONObject();
        if(StringUtils.isEmpty(password) || StringUtils.isEmpty(password)){
            result.put("msg","密码不能为空!");
            result.put("response", ConstantUtils.FAIL);
            return result;
        }
        BasePatientDO patient = basePatientDao.findOne(id);
        if(null == patient){
            result.put("msg","当前居民不存在:【 " + id + "】");
            result.put("response", ConstantUtils.FAIL);
            return result;
        }
        patient.setSalt(randomString(5));
        password = patient.getIdcard().substring(0, 5);
        patient.setPassword(MD5.md5Hex(password + "{" + patient.getSalt() + "}"));
        result.put("response",ConstantUtils.SUCCESS);
        return result;
    }
    /**
     * 修改密码
     * @param id
     * @param newPassword
     * @return
     */
    public JSONObject resetPassword(String id,String newPassword,String captcha){
        JSONObject result = new JSONObject();
        BasePatientDO patient = basePatientDao.findOne(id);
        if(null == patient){
            result.put("msg","当前居民不存在:【 " + id + "】");
            result.put("response", ConstantUtils.FAIL);
            return result;
        }
        patient.setSalt(randomString(5));
        patient.setPassword(MD5.md5Hex(newPassword + "{" + patient.getSalt() + "}"));
        result.put("response",ConstantUtils.SUCCESS);
        return result;
    }
    /**
     * 修改手机号
     * @param id
     * @param newMobile
     * @return
     */
    public JSONObject updateMobile(String id,String newMobile,String captcha){
        JSONObject result = new JSONObject();
        BasePatientDO patient = basePatientDao.findOne(id);
        if(null == patient){
            result.put("msg","当前居民不存在:【 " + id + "】");
            result.put("response", ConstantUtils.FAIL);
            return result;
        }
        if(StringUtils.endsWithIgnoreCase(patient.getMobile(),newMobile)){
            result.put("response",ConstantUtils.SUCCESS);
            return result;
        }
        if(baseSmsService.verifyCaptcha(captcha)){
            patient.setMobile(newMobile);
        }else{
            result.put("msg","验证码不正确或过期!");
            result.put("response", ConstantUtils.FAIL);
            return result;
        }
        result.put("response",ConstantUtils.SUCCESS);
        return result;
    }
//    public JSONObject completePatientDetails(){}
}