fastDFS与spring整合应用

本文介绍了一种使用FastDFS进行图片上传的方法。通过Spring MVC框架的控制器实现文件上传功能,并利用FastDFS_Client库将文件存储到指定服务器。文章详细展示了如何配置FastDFS客户端并处理上传过程中的异常。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package cn.baidu.controller;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import cn.baidu.common.utils.FastDFSClient;
import cn.baidu.common.utils.JsonUtils;

@Controller
public class PictureController {
    
    @Value("${IMAGE_SERVER_URL}")
    private String IMAGE_SERVER_URL;
    //,produces=MediaType.TEXT_PLAIN_VALUE+"charset=utf-8"
    @RequestMapping(value="/pic/upload")
    @ResponseBody
    public String uploadFile(MultipartFile uploadFile){
        System.out.println("+++++++++++++++++++++++++"+uploadFile.toString());
        //把图片上传到图片服务器
        try {
            FastDFSClient fastDFSClient = new FastDFSClient("classpath:conf/client.conf");
            //取文件扩展名
            String originalFilename = uploadFile.getOriginalFilename();
            String extName = originalFilename.substring(originalFilename.lastIndexOf(".")+1);
            //得到图片的地址和文件名
            String url = fastDFSClient.uploadFile(uploadFile.getBytes(), extName);
            //补充为一个完整的url
            url=IMAGE_SERVER_URL+url;
            //封装到map中返回
            Map mapresult=new HashMap<>();
            mapresult.put("error", 0);
            mapresult.put("url", url);
            return JsonUtils.objectToJson(mapresult);
        } catch (Exception e) {
            e.printStackTrace();
            Map mapresult=new HashMap<>();
            mapresult.put("error", 1);
            mapresult.put("message", "图片上传失败");
            return JsonUtils.objectToJson(mapresult);
        }
        
        
    }
}

下面是client.conf

tracker_server=192.168.3.133:22122

使用的是fastDFS_client 1.25的jar包

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值