图片上传到fastDFS服务器

JS中定义方法

     uploadFile:function () {   //文件上传
                var formData = new FormData;  //获取表单对象(HTML5对象)
                formData.append("file",file.files[0]); //表单对象追加file数据
                axios({
                    method:'post',  //请求方式
                    url:'',         //请求URL
                    data:formData,  //发送数据
                    header:{'Content-Type' : "multipart/form-data"} //设置响应头
                }).then(function (response) {
                    if (response.data.status == 200){
                        vue.picEntity.url = response.data.url;
                    }else {
                        alert("图片上传失败");
                    }
                })
            }

在这里插入图片描述

pom.xml导入依赖

<!-- commons-fileupload -->
<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
</dependency>
<!-- fastdfs-client -->
<dependency>
    <groupId>org.csource</groupId>
    <artifactId>fastdfs-client</artifactId>
</dependency>

springmvc.xml配置文件上传解析器

<!-- 配置文件上传解析器  id名称不能更改-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <!-- 设置文件上传默认编码 -->
    <property name="defaultEncoding" value="UTF-8"/>
    <!-- 设置文件上传大小 2MB: 2*1024*1024 -->
    <property name="maxUploadSize" value="2097152"/>
</bean>

Controller后台处理

package com.pinyougou.manager.controller;

import org.apache.commons.io.FilenameUtils;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.StorageClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

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

/**
 * 文件上传/删除Controller
 */
@RestController
public class UploadController {

    @Value("${fileServerUrl}")
    private String fileServerUrl;

    /**
     * 文件上传到fastDFS服务器
     */
    @PostMapping("/upload")
    public Map<String,Object> upload(@RequestParam("file") MultipartFile multipartFile){
        //定义返回的Map
        Map<String,Object> data = new HashMap<>();
        //设置status
        data.put("status",500);
        try {
            //加载配置文件(fastDFS客户端地址)
            String path = this.getClass().getResource("/fastdfs_client.conf").getPath();
            //初始化客户端全局对象
            ClientGlobal.init(path);
            //创建储存客户端对象
            StorageClient storageClient = new StorageClient();
            //获取源上传文件名
            String originalFilename = multipartFile.getOriginalFilename();
            //调用储存客户端对象上传
            String[] strings = storageClient.upload_file(multipartFile.getBytes(), FilenameUtils.getExtension(originalFilename), null);
            //创建StringBuilder拼接url
            StringBuilder url = new StringBuilder();
            url.append(fileServerUrl);
            //迭代拼接
            for (String string : strings) {
                url.append("/" + string);
            }
            //上传成功设置返回MAP
            data.put("status",200);
            data.put("url",url.toString());
            //返回
            return data;
        }catch (Exception e){
            e.printStackTrace();
        }
        return data;
    }

    /**
     * 将文件从fastDFS中删除
     */
    @GetMapping("/delPic")
    public boolean delPic(String url) throws Exception {
        try {
            //获取组名
            int fileNameIndex = url.indexOf("M");
            String fileName = url.substring(fileNameIndex);

            //获取组名
            String[] split = url.split("/");
            String group = split[3];

            //从fastDFS中删除
            String path = this.getClass().getResource("/fastdfs_client.conf").getPath();
            ClientGlobal.init(path);
            StorageClient storageClient = new StorageClient();
            storageClient.delete_file(group,fileName);

            return true;
        }catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }
}


  • 注:
    collection上的value来自上传图片的页面

在这里插入图片描述

  • 在开发中地址不能固定写死,所以用配置文件方式进行使用
    在这里插入图片描述
  • 客户端地址属性文件
    在这里插入图片描述
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值