文件上传图片上传(分布式文件服务器fastDFS)

本文介绍如何在商品录入界面实现多图片上传功能,包括引入FastDFS和commons-fileupload依赖,配置FastDFSClient工具类,设置上传控制器及前端服务,实现文件上传并返回完整URL。

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

在商品录入界面实现多图片上传(后端)
第一步:引入依赖

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

第二步:将“资源/fastDFS/工具类”的 FastDFSClient.java 拷贝到 pinyougou-common 工程

package util;

import org.csource.common.NameValuePair;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.StorageClient1;
import org.csource.fastdfs.StorageServer;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;

public class FastDFSClient {

private TrackerClient trackerClient = null;
private TrackerServer trackerServer = null;
private StorageServer storageServer = null;
private StorageClient1 storageClient = null;

public FastDFSClient(String conf) throws Exception {
	if (conf.contains("classpath:")) {
		conf = conf.replace("classpath:", this.getClass().getResource("/").getPath());
	}
	ClientGlobal.init(conf);
	trackerClient = new TrackerClient();
	trackerServer = trackerClient.getConnection();
	storageServer = null;
	storageClient = new StorageClient1(trackerServer, storageServer);
}

/**
 * 上传文件方法
 * <p>Title: uploadFile</p>
 * <p>Description: </p>
 * @param fileName 文件全路径
 * @param extName 文件扩展名,不包含(.)
 * @param metas 文件扩展信息
 * @return
 * @throws Exception
 */
public String uploadFile(String fileName, String extName, NameValuePair[] metas) throws Exception {
	String result = storageClient.upload_file1(fileName, extName, metas);
	return result;
}

public String uploadFile(String fileName) throws Exception {
	return uploadFile(fileName, null, null);
}

public String uploadFile(String fileName, String extName) throws Exception {
	return uploadFile(fileName, extName, null);
}

/**
 * 上传文件方法
 * <p>Title: uploadFile</p>
 * <p>Description: </p>
 * @param fileContent 文件的内容,字节数组
 * @param extName 文件扩展名
 * @param metas 文件扩展信息
 * @return
 * @throws Exception
 */
public String uploadFile(byte[] fileContent, String extName, NameValuePair[] metas) throws Exception {
	
	String result = storageClient.upload_file1(fileContent, extName, metas);
	return result;
}

public String uploadFile(byte[] fileContent) throws Exception {
	return uploadFile(fileContent, null, null);
}

public String uploadFile(byte[] fileContent, String extName) throws Exception {
	return uploadFile(fileContent, extName, null);
}

}
第三步:配置文件
(1)将“资源/fastDFS/配置文件”文件夹中的 fdfs_client.conf 拷贝到 工程 config 文件夹

# connect timeout in seconds
# default value is 30s
connect_timeout=30

# network timeout in seconds
# default value is 30s
network_timeout=60

# the base path to store log files
base_path=/home/fastdfs

# tracker_server can ocur more than once, and tracker_server format is
#  "host:port", host can be hostname or ip address
tracker_server=192.168.25.133:22122

#standard log level as syslog, case insensitive, value list:
### emerg for emergency
### alert
### crit for critical
### error
### warn for warning
### notice
### info
### debug
log_level=info

# if use connection pool
# default value is false
# since V4.05
use_connection_pool = false

# connections whose the idle time exceeds this time will be closed
# unit: second
# default value is 3600
# since V4.05
connection_pool_max_idle_time = 3600

# if load FastDFS parameters from tracker server
# since V4.05
# default value is false
load_fdfs_parameters_from_tracker=false

# if use storage ID instead of IP address
# same as tracker.conf
# valid only when load_fdfs_parameters_from_tracker is false
# default value is false
# since V4.05
use_storage_id = false

# specify storage ids filename, can use relative or absolute path
# same as tracker.conf
# valid only when load_fdfs_parameters_from_tracker is false
# since V4.05
storage_ids_filename = storage_ids.conf


#HTTP settings
http.tracker_server_port=80

#use "#include" directive to include HTTP other settiongs
##include http.conf

(2)在 工程 application.properties 添加配置 (注入这个配置文件)
FILE_SERVER_URL=http://192.168.25.133/
(3)在 pinyougou-shop-web 工程 springmvc.xml 添加配置:

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
  <property name="defaultEncoding" value="UTF-8"></property>
  <!-- 设定文件上传的最大值 5MB,5*1024*1024 -->
  <property name="maxUploadSize" value="5242880"></property>
</bean>

第四步:新建 UploadController.java

@RestController
public class UploadController {
    @Value("${FILE_SERVER_URL}")
    private String FILE_SERVER_URL;//文件服务器地址
    @RequestMapping("/upload")
    public Result upload( MultipartFile file){
        //1、取文件的扩展名
        String originalFilename = file.getOriginalFilename();
        String extName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        try {
                //2、创建一个 FastDFS 的客户端
                FastDFSClient fastDFSClient = new FastDFSClient("classpath:config/fdfs_client.conf");
                //3、执行上传处理
                String path = fastDFSClient.uploadFile(file.getBytes(), extName);
                //4、拼接返回的 url 和 ip 地址,拼装成完整的 url
                String url = FILE_SERVER_URL + path;
                //返回路径前端可以操作回显示
                return new Result(true,url);
        } catch (Exception e) {
                e.printStackTrace();
                return new Result(false, "上传失败");
        }
    }
}
(前端)

(1)在工程创建 uploadService.js
//文件上传服务层   append中 ‘file’ 的名字决定后端,接收方法中参数 MultipartFile file 的名字,两者对应
app.service("uploadService",function($http){
        this.uploadFile=function(){
            var formData=new FormData();
            formData.append("file",file.files[0]);
            return $http({
                method:'POST',
                url:"../upload.do",
                data: formData,
                headers: {'Content-Type':undefined},
                transformRequest: angular.identity
            });
        }
});

method : 指定方法
url 路径 ,
data formdata上传文件的二进制封装
headers: {‘Content-Type’:undefined}, 不使用默认的json
transformRequest: angular.identity 二进制序列化,formdata
append 中两个参数 : “file”, 决定后端接受参数的名字
file.files[0] : 表示html中第一个为类型(type)为file的 的文件上传属性
anjularjs 对于 post 和 get 请求默认的 Content-Type header 是 application/json。通过设置
‘Content-Type’: undefined,这样浏览器会帮我们把 Content-Type 设置为 multipart/form-data.
通过设置 transformRequest: angular.identity , anjularjs transformRequest function 将序列化
我们的 formdata object.

(2)将 uploadService 服务注入到 goodsController 中

  /**上传图片/
    $scope.uploadFile=function(){
        uploadService.uploadFile().success(function(response) {
            if(response.success){//如果上传成功,取出 url
                $scope.image_entity.url=response.message;//设置文件地址
            }else{
                alert(response.message);
            }
        }).error(function() {
            alert("上传发生错误");
        });
    };

HTML页面初始化

<!--初始化KindEditor-->
<script type="text/javascript">
var editor;
KindEditor.ready(function(K) {
editor = K.create('textarea[name="content"]', {
allowFileManager : true
});
});
</script>

点击上传触发时间

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值