其他分享
首页 > 其他分享> > springboot上传图片

springboot上传图片

作者:互联网

1 controller层

    @PostMapping("/uploadPictrue")
    @ResponseBody
    public Object uploadIconPictrue(@RequestParam("files") MultipartFile[] multipartFiles,
                                    @RequestParam(value = "id",required = false) Long id,
                                    @SessionAttribute("userName") String uname) throws Exception {
        return service.uploadPictrue(multipartFiles[0], id, uname);
    }

2,service层

    //服务器中的位置
    private static final String C_PATH = File.separator + "images" + File.separator + "icon" + File.separator;
    //table表中保存的位置
    private static final String TABLE_PATH = File.separator + "outsource" + File.separator + "icon" + File.separator;

    @Override
    public String uploadPictrue(MultipartFile file, Long id, String updater) throws Exception {
        //保存在服务器中
        saveIconPicTolocation(file);
        //数据表中的icon路径
        String location = TABLE_PATH + file.getOriginalFilename();
        if (id != null) {
            outMapper.updatePath(outsourceTableName, id, updater, location);
        }
        return location;
    }


    private void saveIconPicTolocation(MultipartFile file) throws IOException {
        String location = C_PATH + file.getOriginalFilename();
        InputStream inputStream = null;
        FileOutputStream outputStream = null;
        try {
            inputStream = file.getInputStream();
            byte[] bs = new byte[inputStream.available()];
            inputStream.read(bs);
            outputStream = new FileOutputStream(this.getClass().getClassLoader().getResource("").getPath() + location);
            outputStream.write(bs);
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
            if (outputStream != null) {
                outputStream.close();
            }
        }
    }

  

  

标签:String,File,inputStream,separator,file,图片,上传,id,springboot
来源: https://www.cnblogs.com/pengtaotao/p/15153468.html