zoukankan      html  css  js  c++  java
  • java文件上传

    文件上传的controller

    @Autowired
        private service uploadService;
        @PostMapping("/image")
        public ResponseEntity<String> saveImage(@RequestParam("file")MultipartFile file){
            String url = uploadService.saveImage(file);
            // 判断文件URL是否为空
            if(StringUtils.isEmpty(url)){
                return ResponseEntity.badRequest().build();
            }
            //返回文件的URL
            return ResponseEntity.ok(url);
        }

    service:

    @Service
    public class UpLoadServiceImpl implements service {
        // 定义文件的content_type类型
        private static final List<String> content_type = Arrays.asList("image/jpeg", "image/gif");
        private static final Logger LOGGER = LoggerFactory.getLogger(UpLoadServiceImpl.class);
    
        @Autowired
        private FastFileStorageClient storageClient;
        @Override
        public String saveImage(MultipartFile file) {
            // 获取文件的源名字
            String originalFilename = file.getOriginalFilename();
            String contentType = file.getContentType();
            try {
                //判断文件类型 是否是是图片
                if (!content_type.contains(contentType)) {
                    LOGGER.info("文件类型不符:{}" + originalFilename);
                    return null;
                }
                // 判断内容是否是图片
                BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
                if (bufferedImage == null) {
                    LOGGER.info("文件内容不合法:{}" + originalFilename);
                    return null;
                }
                //保存到本地
                // 普通的文件上传
                //file.transferTo(new File("E:\软件\项目目录\2018\image\" + originalFilename));
                // 使用 fastDFS文件上传
                StorePath uploadFile = this.storageClient.uploadFile(file.getInputStream(), file.getSize(), ".jpg", null);
                //回显url
                return "http://image.leyou.com/"+uploadFile.getFullPath();
            }catch (Exception e){
                LOGGER.info("服务器内部错误:"+originalFilename);
                return null;
            }
    
    
        }
  • 相关阅读:
    el-table背景色透明
    判断数组对象里的属性值是否重复
    :Duplicate keys detected: 'xxx'. This may cause an update error.
    钉钉微应用附件下载方案
    探索JS引擎工作原理
    js深度优先遍历和广度优先遍历实现
    微前端qiankun从搭建到部署的实践
    浏览器与Node的事件循环(Event Loop)有何区别?
    JS
    微信小程序预览Word文档
  • 原文地址:https://www.cnblogs.com/bozhengheng/p/12896677.html
Copyright © 2011-2022 走看看