上传文件到数据库和从库中查询文件

  • 上传

数据库中存放问价的为blob类型,在Java中是byte[]类型

/*
     * 新增闹钟
     * clockType:0、1、2为非自定义闹钟提醒;3、4、5为自定义闹钟提醒
     * */
    @Authorization
    @ResponseBody
    @RequestMapping(value = "/addAlarmClock" , method = RequestMethod.POST)
    public JsonResult addAlarmClock(@CurrentUser User loginUser , HttpServletResponse response,
                                    HttpServletRequest request) {
        Map<String, String> errorMap = new HashMap<String, String>();
        Integer deviceId = Integer.parseInt(request.getParameter("deviceId"));
        Integer clockType = Integer.parseInt(request.getParameter("clockType"));
        String clockTime = request.getParameter("clockTime");
        Integer repeatMon = Integer.parseInt(request.getParameter("repeatMon"));
        Integer repeatTue = Integer.parseInt(request.getParameter("repeatTue"));
        Integer repeatWed = Integer.parseInt(request.getParameter("repeatWed"));
        Integer repeatThu = Integer.parseInt(request.getParameter("repeatThu"));
        Integer repeatFri = Integer.parseInt(request.getParameter("repeatFri"));
        Integer repeatSat = Integer.parseInt(request.getParameter("repeatSat"));
        Integer repeatSun = Integer.parseInt(request.getParameter("repeatSun"));
//        String deviceNo = request.getParameter("deviceNo");

        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;

        Collection<MultipartFile> files = multipartRequest.getFileMap().values();

        //校验
        if (deviceId == null) {
            errorMap.put("deviceId", "设备id不能为空");
            return new JsonResult(false,"设备id参数错误",errorMap);
        }
        if (deviceId <= 0 || deviceId > 2147483647) {
            errorMap.put("deviceId", "设备id范围错误,应是1-2147483647");
            return new JsonResult(false,"设置参数错误",errorMap);
        }
        if (clockType == null) {
            errorMap.put("clockType", "闹钟类型不能为空");
            return new JsonResult(false,"设置参数错误",errorMap);
        }
        if (clockType < 0 || clockType > 5) {
            errorMap.put("clockType", "闹钟类型范围错误,应是0-5");
            return new JsonResult(false,"设置参数错误",errorMap);
        }
        String pattern = "^([01]\\d|2[0123])([0-5]\\d|60)$";
        //闹钟提醒时间
        if (StringUtils.isNotBlank(clockTime) && !Pattern.matches(pattern, clockTime)) {
            errorMap.put("clockTime", "闹钟提醒时间格式错误");
            return new JsonResult(false, "设置参数错误", errorMap);
        }
        if (repeatMon == null || repeatMon < 0 || repeatMon > 1) {
            errorMap.put("repeatMon", "周一是否重复范围错误");
            return new JsonResult(false,"设置参数错误",errorMap);
        }
        if (repeatTue == null || repeatTue < 0 || repeatTue > 1) {
            errorMap.put("repeatTue", "周二是否重复范围错误");
            return new JsonResult(false,"设置参数错误",errorMap);
        }
        if (repeatWed == null || repeatWed < 0 || repeatWed > 1) {
            errorMap.put("repeatWed", "周三是否重复范围错误");
            return new JsonResult(false,"设置参数错误",errorMap);
        }
        if (repeatThu == null || repeatThu < 0 || repeatThu > 1) {
            errorMap.put("repeatThu", "周四是否重复范围错误");
            return new JsonResult(false,"设置参数错误",errorMap);
        }
        if (repeatFri == null || repeatFri < 0 || repeatFri > 1) {
            errorMap.put("repeatFri", "周五是否重复范围错误");
            return new JsonResult(false,"设置参数错误",errorMap);
        }
        if (repeatSat == null || repeatSat < 0 || repeatSat > 1) {
            errorMap.put("repeatSat", "周六是否重复范围错误");
            return new JsonResult(false,"设置参数错误",errorMap);
        }
        if (repeatSun == null || repeatSun < 0 || repeatSun > 1) {
            errorMap.put("repeatSun", "周日是否重复范围错误");
            return new JsonResult(false,"设置参数错误",errorMap);
        }
        /*if (StringUtils.isBlank(deviceNo) || deviceNo.length() > 64) {
            errorMap.put("deviceNo", "设备编码参数范围是1-64");
            return new JsonResult(false,"设置参数错误",errorMap);
        }*/
        if ((clockType == 3 || clockType == 4 || clockType == 5) && files.isEmpty()) {
            errorMap.put("voiceFile", "语音提醒文件为空");
            return new JsonResult(false,"设置参数错误",errorMap);
        }
        //根据Id查找设备是否存在
        Device device = deviceService.deviceShow(deviceId);
        if (device == null || StringUtils.isBlank(device.getDeviceno()) || device.getDevicetype() != 1 ) {
            return new JsonResult(false, "根据deviceId未查询到设备", null);
        }
        //由于指令会出现覆盖的问题,所以在下发前需要查询出该手环之前设置的闹钟提醒
        Map<String,Object> param = new HashMap<>();
        param.put("deviceId",deviceId);
        List<Map<String, Object>> list = watchAlarmClockService.showAll(param);
        if (!CollectionUtils.isEmpty(list) && list.size() == 5) {
            return new JsonResult(false,"闹钟提醒最多只能设置五个",null);
        }

        WatchAlarmClock watchAlarmClock = new WatchAlarmClock();
        byte[] buffer = null;

        //判断文件格式和文件大小
        if (!files.isEmpty()) {
                MultipartFile file = files.toArray(new MultipartFile[0])[0];
                if (file.getSize() > 524288) {
                    return new JsonResult(false,"文件大小限制在64KB以内",null);
                }
            String extensionName = file.getOriginalFilename()
                    .substring(file.getOriginalFilename().lastIndexOf("."));
            if (!extensionName.equals(".amr")) {
                return new JsonResult(false,"文件格式错误,只允许amr格式的文件",null);
            }
            try{
                //将文件转换成byte[]
                buffer = file.getBytes();
                watchAlarmClock.setVoiceData(buffer);
                watchAlarmClock.setIsNeed(1);
            }catch (Exception e ){
                throw new RuntimeException();
            }
        }

        watchAlarmClock.setDeviceId(deviceId);
        watchAlarmClock.setClockSwitch(1);
        watchAlarmClock.setClockTime(clockTime);
        watchAlarmClock.setClockType(clockType);
        watchAlarmClock.setRepeatMon(repeatMon);
        watchAlarmClock.setRepeatTue(repeatTue);
        watchAlarmClock.setRepeatWed(repeatWed);
        watchAlarmClock.setRepeatThu(repeatThu);
        watchAlarmClock.setRepeatFri(repeatFri);
        watchAlarmClock.setRepeatSat(repeatSat);
        watchAlarmClock.setRepeatSun(repeatSun);
        watchAlarmClock.setModifier(loginUser.getUserid());



        String str1 = "";
        for (int i = 0; i <list.size() ; i++) {
            str1 += list.get(i).get("clockType").toString() + "&" + list.get(i).get("clockSwitch").toString() + "&" + list.get(i).get("clockTime") + "&" +
                    list.get(i).get("repeatMon").toString() + list.get(i).get("repeatTue").toString() + list.get(i).get("repeatWed").toString() +
                    list.get(i).get("repeatThu").toString() + list.get(i).get("repeatFri").toString() + list.get(i).get("repeatSat").toString() +
                    list.get(i).get("repeatSun").toString() + "%" ;
        }
        String clocks = str1 + clockType.toString() + "&1&" + clockTime + "&" + repeatMon.toString() + repeatTue.toString() +
                repeatWed.toString() + repeatThu.toString() + repeatFri.toString() + repeatSat.toString() + repeatSun.toString();

        //添加闹钟提醒
        int n = watchAlarmClockService.save(watchAlarmClock);
        if (n <= 0) {
            return new JsonResult(false, "添加失败", null);
        }

        h002.setAlarmClock(device.getDeviceno(),clocks);
        //判断是否是自定义的闹钟,自定义的闹钟会有语音提醒文件
        if (clockType == 3 || clockType == 4 || clockType == 5) {
            h002.setVoiceFile(device.getDeviceno());
        }

        return new JsonResult(true, "设置成功.", null);
    }
  • 查询
    /*
         * 根据id查询某条提醒的语音文件
         * */
        @ResponseBody
        @RequestMapping(value = "/selectFileById")
        public JsonResult selectFileById(Integer id,HttpServletRequest request,HttpServletResponse response) throws IOException {
            if (id == null || id <= 0 || id > 2147483647) {
                return new JsonResult(false, "参数错误", null);
            }
            WatchAlarmClock watchAlarmClock = watchAlarmClockService.selectByid(id);
            if (watchAlarmClock == null) {
                return new JsonResult(false, "没有此id", null);
            }
            byte[] data = watchAlarmClock.getVoiceData();
    
            String fileName = watchAlarmClock.getId().toString() + ".amr";
    //        System.out.println("fileName: " + fileName);
            fileName = URLEncoder.encode(fileName, "UTF-8");
            response.reset();
            response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
            response.addHeader("Content-Length", "" + data.length);
            response.setContentType("application/octet-stream;charset=UTF-8");
            OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
            outputStream.write(data);
            outputStream.flush();
            outputStream.close();
            return new JsonResult(true, "查询成功", null);
        }

     

 

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 可以使用MybatisPlus提供的Blob字段类型来存储文件数据,具体实现可以参考MybatisPlus官方文档的Blob字段类型使用方法。同时,也可以使用MybatisPlus提供的注解@TableField和@TableName来映射数据库表和字段。 ### 回答2: 使用MyBatis Plus将文件上传数据库的一般步骤如下: 1. 创建数据库表:首先需要创建一个包含文件内容的字段的数据库表。可以使用如下SQL语句创建一个名为file_table的表: ```sql CREATE TABLE file_table ( id INT PRIMARY KEY AUTO_INCREMENT, file_data LONGBLOB ); ``` 2. 创建实体类:使用Java创建一个实体类,该实体类将映射到数据库表。实体类需要有一个数据库表对应的字段,并使用`@TableName`注解标识表名和`@TableField`注解标识字段名。 ```java import com.baomidou.mybatisplus.annotation.TableName; @TableName("file_table") public class FileEntity { private Long id; private byte[] fileData; // getters and setters } ``` 3. 编写Mapper接口:编写一个继承`BaseMapper`的Mapper接口,用于执行数据库操作。可以使用MyBatis Plus提供的`BaseMapper`接口的默认实现。 ```java import com.baomidou.mybatisplus.core.mapper.BaseMapper; public interface FileMapper extends BaseMapper<FileEntity> { } ``` 4. 使用Mapper进行存储:通过调用Mapper的方法将文件内容存储到数据库。 ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.multipart.MultipartFile; import java.io.IOException; @Service @Transactional public class FileService { @Autowired private FileMapper fileMapper; public void uploadFile(MultipartFile file) throws IOException { FileEntity fileEntity = new FileEntity(); fileEntity.setFileData(file.getBytes()); fileMapper.insert(fileEntity); } } ``` 这样,上传文件内容将以byte数组的形式存储到数据库。在其他地方可以通过查询该数据表并读取byte数组,来获取文件内容。 ### 回答3: 使用Mybatis Plus上传文件数据库,可以参考以下步骤: 1. 首先,创建一个实体类,用于映射数据库的字段。例如,你可以创建一个FileEntity类,包含文件的名称、类型、大小和二进制数据等属性。 2. 在数据库创建相应的表,用于存储上传文件数据。表的字段设计可以参考FileEntity类的属性。 3. 在Mybatis Plus的配置文件,配置数据源信息和mapper扫描路径。 4. 创建一个Mapper接口,在接口定义数据库操作方法。例如,你可以创建一个FileMapper接口,定义一个insert方法,用于向数据库插入文件数据。 5. 创建对应的Mapper.xml文件,实现FileMapper接口定义的数据库操作方法。在该文件,编写插入语句,将文件数据插入到数据库。 6. 在业务逻辑,调用FileMapper接口的insert方法,将文件数据持久化到数据库。 7. 在上传文件的Controller,获取前端传递的文件数据,并将文件数据转为FileEntity对象。然后,调用业务逻辑的插入方法,将文件数据保存到数据库。 总结: 使用Mybatis Plus上传文件数据库,首先需要创建实体类和数据库表,并配置好Mybatis Plus的数据源和mapper扫描路径。然后,通过Mapper接口和Mapper.xml文件,实现文件数据的插入操作。最后,在业务逻辑,将文件数据保存到数据库
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值