2020-10-30

关于boot批量上传图片后台代码


前言

直接啥都不说了直接上代码,看到代码的有缘人能给我提一点代码优化的建议吗


一、Controller代码

@ApiOperation(value="图片上传功能批量上传")
@RequestMapping(value = "/uploadBatch", method = {RequestMethod.GET,RequestMethod.POST})
public BaseResponse<Map<String, Boolean>> uploadBatch(@RequestParam("file")MultipartFile[] file, 					   StUploadImageParam param) throws Exception {
    Map map = new HashMap();
    if(file.length<1){
        throw new Exception("没有上传图片信息请核对!!!");
    }
    try{
        Assert.notNull(param.getStcd(),"测站编码不能为空");
        fileService.uploadBatch(file,param);
        map.put("success",true);
        return buildSuccessResponse(map);
    }catch (Exception e){
        e.printStackTrace();
        map.put("success",false);
        return buildSuccessResponse(map);
    }
}

二、Service代码

@Override
public void uploadBatch(MultipartFile[] file, StUploadImageParam param) throws IOException {
    FileFilterTool.mkdir(path);
    List<StUploadImageParam> list = new ArrayList<>();
    InetAddress address = InetAddress.getLocalHost();
    String str = address.toString().substring(address.toString().lastIndexOf("/")+1);

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:MM:ss");
    StStbprpBParam key = new StStbprpBParam();
    key.setStcd(param.getStcd());
    List<StStbprpB> stcdList = stStbprpBService.selectStcdForPrimary(key);
    if(null == stcdList || stcdList.size() < 1){
        param.setStnm("");
    }else {
        param.setStnm(stcdList.get(0).getStnm());
    }
    for(int i=0;i<file.length;i++){
        StUploadImageParam param1 = new StUploadImageParam();
        String uuid = UUID.randomUUID().toString();
        String filename = uuid+File.separator+file[i].getOriginalFilename();
        File saveFile = new File(path+filename);
        FileFilterTool.mkdir(path+File.separator+uuid);
        OutputStream outputStream = new FileOutputStream(saveFile);
        param1.setUrl("http://"+str+":"+port+"/image2/"+filename);
        param1.setUuid(uuid);
        param1.setStcd(param.getStcd());
        param1.setStnm(param.getStnm());
        param1.setTm(new Date());
        param1.setFileName(file[i].getOriginalFilename());
        list.add(param1);
        try{
            IOUtils.copy(file[i].getInputStream(),outputStream);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            outputStream.close();
        }
    }
    fileDAO.insertInfoBatch(list);
}

1.逻辑说明

图片上传到某一文件夹下面后要在数据库保留存储信息以便前台展示用,和信息说明,再一个boot存储图片需要设置一个文件可以访问的静态区,自己在网上去搜挺多的,代码不足的地方和不规范的地方请各位大佬指点一二不胜感激

©️2020 CSDN 皮肤主题: 数字20 设计师:CSDN官方博客 返回首页