SpringMVC+AngualrJS实现文件上传到fastDFS服务器

SpringMVC+AngualrJS实现文件上传到fastDFS服务器

后端

  1. 引入依赖

    <!-- 文件上传组件 -->
    <dependency>
    	<groupId>org.csource.fastdfs</groupId>
    	<artifactId>fastdfs</artifactId>
    </dependency>
    <dependency>
    	<groupId>commons-fileupload</groupId>
    	<artifactId>commons-fileupload</artifactId>
    </dependency>
    
  2. 使用上传文件的工具类实现操作

    /**
     * 文件上传 工具类
     */
    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);
       }
       
       /**
        * 上传文件方法
        * <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);
       }
    }
    
  3. 在sources下添加配置文件 application.properties : 存储请求图片的路径(http:10.207.130.187/)
    FILE_SERVER_URL=http://10.207.130.187:9991/

  4. 添加fastDFS的配置文件: fdfs_client.conf ,配置“tracker_server”

	tracker_server=10.207.130.187:22122
  1. 在springmvc的配置文件中配置

    1. 读取存储请求图片路径的配置文件

      <!--读取配置文件的内容-->
      <context:property-placeholder location="classpath:config/application.properties" />
      
    2. 配置springmvc的多媒体解析器

      <!-- 配置SpringMVC多媒体解析器,id只能是这个名字 -->
      <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>
      
  2. 编写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

  1. 编写service

    //文件上传的前端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
              });
          }
      });
    
  2. 在controller中引入uploadService,定义方法

    //图片上传
      $scope.uploadFile = function () {
      	uploadService.uploadFile().success(function (response) {
      		if(response.flag){	//上传成功
      			$scope.image_entity.url =response.message;	//获取图片上传后的url
      		}else{
      			alert(response.message);    //上传失败
      		}
           })
       }
    
  3. 页面端。
    需要额外引入uploadService.js文件

   	 <script type="text/javascript" src="../js/service/uploadService.js"></script>
  1. 在表单中绑定 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>
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值