<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>
fastDFS的配置文件fast_client.conf全文以下(resources/properties/fdfs_client.conf)html
#把此文件放入工程中所需的模塊的resources/config目錄下,經過FastDFSClient工具類的構造方法加載便可,通常只需修改tracker_server #使用舉例,controller #//獲取從properties文件中定義的的tracker server的值 # @Value("${FILE_SERVER_URL}") # private String FILE_SERVER_URL; # # @RequestMapping("/uploadFile") # public Result uploadFile(MultipartFile file) { # try { # String originalFilename = file.getOriginalFilename(); # String extName = originalFilename.substring(originalFilename.indexOf(".") + 1); # # FastDFSClient fastDFSClient = new FastDFSClient("classpath:/config/fdfs_client.conf"); # String s = fastDFSClient.uploadFile(file.getBytes(), extName); # return new Result(true, FILE_SERVER_URL + s); # } catch (Exception e) { # return new Result(false, "upload failed!"); # } # } # 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
將上方的tracker_server的屬性更改成本身的主機ip【個人是192.168.25.133:22122】前端
# tracker_server can ocur more than once, and tracker_server format is
# "host:port", host can be hostname or ip address,修改爲本身tracker_server的ip地址和端口號,默認22122
tracker_server=192.168.25.133:22122
將本地目錄的F:\\image\\01.jpg文件上傳至服務器html5
public class fastDFSDemo { public static void main(String[] args) throws Exception { // 一、 加載配置文件, 配置文件中的內容就是 tracker 服務的地址。 ClientGlobal.init("F:\\coding\\helloFastDFS\\src\\main\\resources\\fdfs_client.conf"); // 二、 建立一個 TrackerClient 對象。 直接 new 一個。 TrackerClient trackerClient=new TrackerClient(); // 三、 使用 TrackerClient 對象建立鏈接, 得到一個 TrackerServer 對象。 TrackerServer trackerServer = trackerClient.getConnection(); // 四、 建立一個 StorageServer 的引用, 值爲 null StorageServer storageServer=null; // 五、 建立一個 StorageClient 對象, 須要兩個參數 TrackerServer 對象、 StorageServer的引用 StorageClient1 storageClient1=new StorageClient1(trackerServer,storageServer); // 六、 使用 StorageClient 對象上傳圖片。 String[] strings = storageClient1.upload_appender_file("F:\\image\\01.jpg","jpg", null); // 七、 返回數組。 包含組名和圖片的路徑。 for (String string : strings) { System.out.println(string); } } }
運行結果java
group1
M00/00/00/wKgZhV0p3meEboMrAAAAAOo7as0657.jpg
圖片的加載是依賴於negix加載的,默認端口號80,訪問路徑以下
http://192.168.25.133/group1/M00/00/00/wKgZhV0p3AqESvEmAAAAAOo7as0348.jpgangularjs
略web
不配置的話會在文件上傳的時候拋出沒法解析的異常。spring
<!--文件上傳的多媒體解析器 主要配置:限制文件大小 配置字符集編碼--> <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>
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); } }
@RestController @RequestMapping("/upload") public class UploadController { @Value("${FILE_SERVER_URL}") private String FILE_SERVER_URL; @RequestMapping("/uploadFile") public Result uploadFile(MultipartFile file) { try { String originalFilename = file.getOriginalFilename(); String extName = originalFilename.substring(originalFilename.indexOf(".") + 1); FastDFSClient fastDFSClient = new FastDFSClient("classpath:/config/fdfs_client.conf"); String s = fastDFSClient.uploadFile(file.getBytes(), extName); return new Result(true, FILE_SERVER_URL + s); } catch (Exception e) { return new Result(false, "upload failed!"); } } }
<context:property-placeholder location="classpath:config/application.properties"/> <mvc:annotation-driven> <mvc:message-converters register-defaults="true"> <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter"> <property name="supportedMediaTypes" value="application/json"/> <property name="features"> <array> <value>WriteMapNullValue</value> <value>WriteDateUseDateFormat</value> </array> </property> </bean> </mvc:message-converters> </mvc:annotation-driven>
FILE_SERVER_URL=http://192.168.25.133/
以angularJS爲例實現前端文件上傳的代碼json
前端頁面數組
<input type="file" id="file" /><br/>
<button ng-click="uploadFile()" class="btn btn-primary" type="button" >上傳</button><br/>
<img src="{{entity.pic}}" width="200px" height="100px">
controller中被調用的方法服務器
$scope.entity = {}; $scope.uploadFile = function () { uploadService.uploadFile().success( function (response) { $scope.entity.pic = response.message; } ) }
uploadService中的方法
//服務層 app.service('uploadService',function($http){ //文件上傳 this.uploadFile=function(){ //基於angularjs結合html5(FormData)完成文件上傳 <form> var formData = new FormData(); //要基於定義的表單數據對象,獲取頁面選擇的文件對象 //參數一:與後臺java代碼接收文件對象的參數名一致 //參數二:獲取頁面的文件對象 file.files[0] file與<input type="file" id="file" />中的id保存一致 formData.append("file",file.files[0]); return $http({ url: "../upload/uploadFile.do", method:"post", data:formData, headers : {'Content-Type' : undefined}, //上傳文件必須是這個類型,默認text/plain,至關於配置了enctype="multipart/form-data" transformRequest : angular.identity //對整個表單進行二進制序列化 }); } });