如何使用fastDFS在angularjs中實作檔案上傳:
- 先在後端引入相關的jar包:
<dependency> <groupId>org.csource.fastdfs</groupId> <artifactId>fastdfs</artifactId> <version>1.2</version> </dependency> <!-- 檔案上傳元件 --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency>
- 配置工具類:
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); } }
2.1 讀取配置檔案:
application.properties配置檔案内容:FILE_SERVER_URL=http://192.168.25.133/
fdfs_client.conf配置檔案内容:
# 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
- 後端Controller代碼:
@RestController
@RequestMapping("/upload")
public class UploadFileController {
//注解注入:讀取properties檔案,通過檔案擷取(url)(FILE_SERVER_URL=http://192.168.25.133/)
@Value("${FILE_SERVER_URL}")
private String fileServerUrl;
@RequestMapping("/img")
public Result img(MultipartFile file){
//加載配置檔案
FastDFSClient client;
try {
client = new FastDFSClient("D:\\eclipse\\eclipse_Project\\pinyougou-parent\\pinyougou-shop-web\\src\\main\\resources\\config\\fdfs_client.conf");
//擷取上傳檔案的全名
String originalFilename = file.getOriginalFilename();
//切割檔案全名,擷取檔案的字尾名(.jpg)
String fileName = originalFilename.substring(originalFilename.lastIndexOf(".")+1);
//通過工具類的方法,以位元組形式上傳檔案
String uploadFile = client.uploadFile(file.getBytes(),fileName);
//上傳成功:傳回檔案的通路路徑
return new Result(true,fileServerUrl+uploadFile);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
//上傳失敗:傳回上傳失敗
return new Result(false,"上傳失敗");
}
}
}
- 前端頁面代碼:
<td>
<input type="file" id="file" />
<!-- 當使用者選中圖檔,然後點選上傳,會調用綁定的ng-click事件,然後把傳回的圖檔通路連接配接 使用angular表達式給到下面img标簽的src屬性中,這樣就可以展示使用者上傳的圖檔了 -->
<button class="btn btn-primary" type="button" ng-click="uploadFile()">
上傳
</button>
</td>
<td>
<img src="{{img_entity.url}}" width="200px" height="200px">
</td>
- 前端service.js代碼 :
//服務層
app.service("uploadService", function ($http) {
//上傳檔案
this.uploadFile = function () {
var fomtdata = new FormData();
//file.files 等于 document.getElementById("file").files[0];擷取id為file的file上傳檔案框的内容,0為key
fomtdata.append("file", file.files[0]);
return $http({
url: "../upload/img.do",
method: "post",
data: fomtdata,
//設定請求頭,等于把請求頭設定為multipart/form-data
headers: { "Content-Type": undefined },
transformRequest: angular.identity //讓檔案以二進制傳輸(序列化);
})
}
})
- 前端controller.js代碼:
//控制層
app.controller('goodsController', function ($scope, uploadService) {
$scope.img_entity = { url: "", color: "" };//定義對象
//上傳檔案
$scope.uploadFile = function () {
uploadService.uploadFile().success(
function (response) {
if (response.flag) {
//如果上傳成功,把響應回來的檔案通路連結指派給$scope.img_entity.url
$scope.img_entity.url = response.msg;
} else {
alert("上傳失敗");
}
}
)
}