首页 > 编程语言 > 详细

java文件上传

时间:2020-05-15 21:33:08      阅读:60      评论:0      收藏:0      [点我收藏+]

文件上传的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;
        }


    }

 

java文件上传

原文:https://www.cnblogs.com/bozhengheng/p/12896677.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!