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;
        }


    }

 

posted @ 2020-05-15 19:15  刀锋意志1  阅读(407)  评论(0编辑  收藏  举报