SpringMVC+AngualrJS実装ファイルfastDFSサーバへのアップロード


SpringMVC+AngualrJS実装ファイルfastDFSサーバへのアップロード
バックエンド
  • 依存
    <!--        -->
    <dependency>
    	<groupId>org.csource.fastdfs</groupId>
    	<artifactId>fastdfs</artifactId>
    </dependency>
    <dependency>
    	<groupId>commons-fileupload</groupId>
    	<artifactId>commons-fileupload</artifactId>
    </dependency>
    
  • を導入する.
  • ファイルをアップロードするツールクラスを使用して動作
    /**
     *         
     */
    public class FastDFSClient {
    
       private TrackerClient trackerClient = null;
       private TrackerServer trackerServer = null;
       private StorageServer storageServer = null;
       private StorageClient1 storageClient = null;
    
       /**
        *       ,         storageClient  
        * @param conf
        * @throws Exception
        */
       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); } }
  • を実現する.
  • sourcesの下にプロファイルアプリケーション.propertiesを追加:要求ピクチャを格納するパス(http:0.207.130.1187/)FILE_SERVER_URL=http://10.207.130.187:9991/
  • fastDFSのプロファイルを追加:fdfs_Client.conf,構成"tracker_server"
  • 	tracker_server=10.207.130.187:22122
    
  • springmvcのプロファイルで構成
  • 要求ピクチャパスを記憶するプロファイル
    
    <context:property-placeholder location="classpath:config/application.properties" />
    
  • を読み出す.
  • springmvcを構成するマルチメディア解析器
    
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
       <property name="defaultEncoding" value="UTF-8">property>
       
       <property name="maxUploadSize" value="5242880">property>
    bean>
    
  • controller層
    /**
      *	        
      */
    
     @RestController
     public class UploadController {
    
       /**
        *             ("http:10.207.130.187/")
        */
       @Value("${FILE_SERVER_URL}")
       private String file_server_url;
    
       /**
        *     ,  “MultipartFile”  
        * @return
        */
       @RequestMapping("/upload.do")
       public ResultInfo uploadFile(MultipartFile file){
           //          
           String originalFilename = file.getOriginalFilename();	//       (     )
           String txName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);	//     ,  "."
           try {
               //         fdfs_client.conf,  FastDFSClient     
               FastDFSClient fastDFSClient = new FastDFSClient("classpath:config/fdfs_client.conf");
               //    ,    file_id(     )
               String path = fastDFSClient.uploadFile(file.getBytes(), txName);
               //    (         )   
               return new ResultInfo(true,file_server_url + path);
           } catch (Exception e) {
              return new ResultInfo(false,"    ,     ");
          }
      }
     }
    
  • を記述する
    フロントエンド
    画像のアップロードとエコー、angularJSの使用
  • 作成サービス
    //       service
      app.service('uploadService',function ($http) {
          this.uploadFile = function () {
              //  FormData  ,H5         
              var formData = new FormData();
              formData.append("file",file.files[0]);//(file:        name)
              return $http({
                  method:'post',
                  url:'../upload.do',
                  data:formData,
                  headers: {'Content-Type':undefined},
                  transformRequest: angular.identity
              });
          }
      });
    
  • controllerにuploadServiceを導入し、定義方法
    //    
      $scope.uploadFile = function () {
      	uploadService.uploadFile().success(function (response) {
      		if(response.flag){	//    
      			$scope.image_entity.url =response.message;	//        url
      		}else{
      			alert(response.message);    //    
      		}
           })
       }
    
  • ページ端.uploadServices.jsファイル
  • の追加導入が必要です.
       	 <script type="text/javascript" src="../js/service/uploadService.js">script>
    
  • フォームにng-modul,ng-click.ピクチャを表示するsrcはcontrollerで取得したurlに設定される.「アップロード」をクリックしてcontrollerのメソッド
    <table>
    	<tr>
    		<td>
    		<input type="file" id="file" />				                
                 <button class="btn btn-primary" type="button" ng-click="uploadFile()" >
                 		  
                 button>	
             td>
    		<td>
    			<img  src="{{image_entity.url}}" width="200px" height="200px">
    		td>
    	tr>						
    table>
    
  • を呼び出します.