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

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


org.csource.fastdfs
fastdfs


commons-fileupload
commons-fileupload

第二步:将“资源/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);
}/*** 上传文件方法* 

Title: uploadFile

*

Description:

* @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); }/*** 上传文件方法*

Title: uploadFile

*

Description:

* @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 添加配置:



第四步:新建 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 地址,拼装成完整的 urlString 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页面初始化



点击上传触发时间


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部