Fastdfs分布式文件系统(图片上传)代码共享

1 需求分析
在商品录入界面实现多图片上,当用户点击新建按钮,弹出上传窗口,点击上传按钮后回显上传图片,点击该对话框的保存按钮,把图片封装到该页面的一个公共属性里与自己需要上传的字段对应的字段里
注意这里我们有两个上传按钮,一个上传,一个按钮,当我们点击上传时,图片只是保存到了fastDfs图片服务器里了,并没有保存到数据库,点击保存时只是将图片地址封装了,也没有保存   只有当点击页面的保存时才和其他数据一起保存到数据库


简单上传代码实现:
1.导jar
<!-- 文件上传组件 -->
  <dependency>
      <groupId>org.csource.fastdfs</groupId>
      <artifactId>fastdfs</artifactId>
  </dependency>
  <dependency>
   <groupId>commons-fileupload</groupId>
   <artifactId>commons-fileupload</artifactId>
  </dependency>
2.创建一个client.conf  文件     内容写上你的fastDfs服务器的ip    到config文件夹中,并在springMVC.xml文件中配置文件让其能查找到这个文件 
FILE_SERVER_URL=http://192.168.25.133/
3. springmvc.xml 添加配置
<!-- 配置多媒体解析器 -->
        < bean id = "multipartResolver"
              < property name = "defaultEncoding" value = "UTF-8" ></ property >
              <!-- 设定文件上传的最大值 5MB,5*1024*1024 -->
              < property name = "maxUploadSize" value = "5242880" ></ property >
        </ bean >




<!--扫描config文件夹下的所有properties文件-->
<context:property-placeholder location="classpath:config/*.properties" />

4.完成上传操作的后端代码文件  UploadController.java    并且导入文件上传的工具包  完成上传操作

resources.properties
IMAGE_SERVER_URL= http://192.168.25.133/


PygResult:这是我封装的一个布尔类,好用来返回是否成功在页面显示,可用可不用
        //注入常量配置
        @Value ( "${IMAGE_SERVER_URL}" )
        private String IMAGE_SERVER_URL ;

@RequestMapping ( "/upload" )
public PygResult uploadPic(MultipartFile file ){
             
             
              try {
                     //获取文件名称
                    String originalFilename = file .getOriginalFilename();
                     //截取文件扩展名
                    String extName = originalFilename .substring( originalFilename .lastIndexOf( "." )+1);
                    
                     //创建工具类对象 加载client.conf文件里的fastDfs服务器地址
                     FastDFSClient fdfs = new FastDFSClient ( "classpath:config/client.conf" );
                     //上传文件
                     // gif , bmp , jpg
                     //返回文件上传成功地址:group1/M00/00/02/wKhCQ1qvKG2AZqibAA1rIuRd3Es806. jpg
                    String url = fdfs .uploadFile( file .getBytes(), extName );
                    
                     //组合图片上传成功绝对地址
                    //  url = "fastDfs图片服务器IP地址"+url;  这样写会吧IP暴露出来,我们可以创建一个resources.properties文件,里面放上我们的IP 再使用  @Value注入即可  (注意如写了这个文件在springMVC.xml中要配置一个扫描器扫描这个文件)
                     url = IMAGE_SERVER_URL + url ;
                    System. out .println( "地址:=============" + url );
                     //上传成功
                     return new PygResult( true , url );
                    
                    
             } catch (Exception e ) {
                     // TODO Auto-generated catch block
                     e .printStackTrace();
                     //上传失败
                     return new PygResult( false , "上传失败" );
             }
             
             
       }



前端代码实现:
有上传页面如下   当点击新建窗口是跳转到文件上传标签  在里面进行上传    上传后返回图片地址在页面回显
<!-- 上传窗口 -->
       <div class="modal fade" id="uploadModal" tabindex="-1" role="dialog"
             aria-labelledby="myModalLabel" aria-hidden="true">
             <div class="modal-dialog">
                    <div class="modal-content">
                           <div class="modal-header">
                                 <button type="button" class="close"  data-dismiss="modal"
                                        aria-hidden="true">×</button>
                                 <h3 id="myModalLabel">上传商品图片</h3>
                           </div>
                           <div class="modal-body">
                                 <table class="table table-bordered  table-striped">
                                        <tr>
                                               <td>颜色</td>
                                               <td><input class="form-control"  placeholder="颜色"
                                                      ng-model="imageEntity.color"></td>
                                        </tr>
                                        <tr>
                                               <td>商品图片</td>
                                               <td>
                                                     <table>
                                                            <tr>
                                                                   <td><input  type="file" id="file" />
                                                                          <button class="btn btn-primary" type="button"
                                                                                 ng-click="uploadFile()">上传</button></td>
                                                                   <td> <img  src="{{imageEntity.url}}" width="200px"
                                                                          height="200px"></td>
                                                            </tr>
                                                     </table>
                                               </td>
                                        </tr>
                                 </table>
                           </div>
                           <div class="modal-footer">
                                 <button class="btn btn-success"  ng-click="add_image_entity()"
                                        data-dismiss="modal"  aria-hidden="true">保存</button>
                                 <button class="btn btn-default"  data-dismiss="modal"
                                        aria-hidden="true">关闭</button>
                           </div>
                    </div>
             </div>
       </div>
1.创建uploadContrlller.js  uploadService.js文件  并在页面引用  (因为我们使用的时 angularjs插件,具体使用看angularjs的配置介绍使用


在uploadContrlller.js 中完成上传方法并调用uoloapservice.js方法,
app.controller('goodsController' ,function($scope,$controller,uploadService){ 
$controller('baseController',{$scope:$scope});//继承
// 文件上传
    $scope.uploadFile = function() {
        // 调用服务层
        uploadService.uploadFile().success(function(data) {
            // 是否上传成功
            if (data.success) {
                // 把图片地址获取  返回图片地址  在页面调用即可回显
                $scope.imageEntity.url = data.message;
            } else {
                // 上传失败
                alert("上传失败");
            }
        });
    };
=========================================华丽的分割线==============================================
    // 定义初始化对象
    $scope.entity = {
        goods : {},
        goodsDesc : {
            itemImages : [],
            specificationItems : []
        }
    };
    // 保存图片操作
    // 保存图片:只需要利用数据双向绑定原理,获取到图片上传数据,把数据绑定到需要保存entity实体即可
    $scope.add_image_entity = function() {
        // 把图片对象数据添加到商品描述对象
        $scope.entity.goodsDesc.itemImages.push($scope.imageEntity);
    }

    // 删除图片对象
    $scope.removeImageEntity = function(index) {
        $scope.entity.goodsDesc.itemImages.splice(index, 1);
    }
});

2.uploadService.js完成方法,并连接后端代码返回参数
//抽取服务
app.service( "uploadService" , function ($http) {
        //文件上传
        this .uploadFile= function (){
             
              var formData= new FormData();
             formData.append( 'file' ,file.files[0]);
             
              return $http({
                    method: 'POST' ,
                    url: '../shop/upload'//这里的../shop/upload  时java代码中的地址和方法名 @RequestMapping("/shop")
                    data:formData,
                    headers:{ 'Content-Type' : undefined }, // angularjs 自动识别类型为 multipart / formdata 类型
                    transformRequest: angular.identity
                    });
             
       };
});

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序猿邱先森

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值