品優購day05——商家後臺-商品錄入(商品圖片)

商家後臺-商品錄入【商品圖片上傳】

6.1需求分析

在商品錄入界面實現多圖片上傳

當用戶點擊新建按鈕,彈出上傳窗口

6.2後端代碼

6.2.1 工具類

(1)pinyougou-common工程pom.xml引入依賴

 

        <!-- 文件上傳組件 -->

        <dependency>

            <groupId>org.csource.fastdfs</groupId>

            <artifactId>fastdfs</artifactId>

        </dependency>

        <dependency>

            <groupId>commons-fileupload</groupId>

            <artifactId>commons-fileupload</artifactId>

        </dependency>  

(2)將“資源/fastDFS/工具類”的FastDFSClient.java 拷貝到pinyougou-common工程

配置文件

  1. 將“資源/fastDFS/配置文件”文件夾中的 fdfs_client.conf 拷貝到pinyougou-shop-web工程config文件夾

(2)在pinyougou-shop-web工程application.properties添加配置

#圖片服務器
FILE_SERVER_URL=http://192.168.25.133/

 

在pinyougou-shop-web工程springmvc.xml添加配置:

<!-- 配置多媒體解析器 -->

<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>


控制層

在pinyougou-shop-web 新建UploadController.java

package com.pinyougou.shop.controller;

import com.pinyougou.entity.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import utils.FastDFSClient;

/**
 * @Auther: jun
 * @Date: 2018/8/22 0022 17:54
 * @Description: 圖片上傳Controller
 */
@RestController
public class UploadController {
    @Value ("${FILE_SERVER_URL}")
    private String FILE_SERVER_URL;
    @RequestMapping("/upload")
    public Result upload(MultipartFile file){
        try {
            //獲取文件名
            String filename = file.getOriginalFilename ();
            //獲取擴展名
            String extName = filename.substring (filename.indexOf (".") + 1);
            //使用我們的FastDFSClient工具類讀取fdfs的配置文件
            FastDFSClient client=new FastDFSClient ("classpath:config/fdfs_client.conf");
           //調用上傳功能並返回一個圖片服務器上圖片的id
            String fileId  = client.uploadFile (file.getBytes (), extName);
            //拼接一個完整的可以訪問圖片服務器的路徑地址
            String url=FILE_SERVER_URL+fileId;
            return new Result (true,url);
        } catch (Exception e) {
            e.printStackTrace ();
            return new Result (false,"上傳失敗!");
        }
    }
}

前端代碼

6.3.1 服務層

(1)在pinyougou-shop-web工程創建uploadService.js

//服務層
app.service('uploadService',function($http){
    //上傳文件
    this.uploadFile=function () {
        //h5新增的獲取到表單數據
        var formatData = new FormData();
        formatData.append('file',file.files[0]);//file 文件上傳框的name

        return $http({
            url:'../upload.do',
            method:'post',
            data:formatData,
            headers:{'Content-Type':undefined},//上傳圖片的設置頭信息
            transformRequest: angular.identity  //表單的二進制序列化
        });
    }
});

anjularjs對於post和get請求默認的Content-Type header 是application/json。通過設置‘Content-Type’: undefined,這樣瀏覽器會幫我們把Content-Type 設置爲 multipart/form-data.

通過設置 transformRequest: angular.identity ,anjularjs transformRequest function 將序列化我們的formdata object.

(2)將uploadService服務注入到goodsController 中

 

//商品控制層(商家後臺)

app.controller('goodsController' ,function($scope,$controller   ,goodsService,itemCatService,uploadService){

(3)在goods_edit.html引入js

<script type="text/javascript" src="../js/base.js">  </script>

<script type="text/javascript" src="../js/service/goodsService.js">  </script>

<script type="text/javascript" src="../js/service/itemCatService.js">  </script>

<script type="text/javascript" src="../js/service/uploadService.js">  </script>

<script type="text/javascript" src="../js/controller/baseController.js">  </script>

<script type="text/javascript" src="../js/controller/goodsController.js">  </script>

6.3.2 上傳圖片

(1)goodsController編寫代碼

    //上傳圖片
	$scope.uploadFile=function () {
		uploadService.uploadFile().success(function (response) {
			if (response.success){
				$scope.image_entity.url=response.message;//將上傳成功的url地址綁定到img的src上
			} else {
				alert(response.message);
			}
        })
    }

(2)修改圖片上傳窗口,調用上傳方法,回顯上傳圖片

        <div class="modal-body">           

            <table class="table table-bordered table-striped">

                 <tr>

                     <td>顏色</td>

                     <td><input  class="form-control" placeholder="顏色" ng-model="image_entity.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="{{image_entity.url}}" width="200px" height="200px">

                                </td>

                            </tr>                      

                        </table>

                     </td>

                 </tr>               

             </table>          

        </div>

修改新建按鈕

<button type="button" class="btn btn-default" title="新建" data-target="#uploadModal"  data-toggle="modal" ng-click="image_entity={}" ><i class="fa fa-file-o"></i> 新建</button>

 

6.3.3 圖片列表

(1)在goodsController.js增加方法

    //將上傳成功的圖片信息添加到圖片列表中
    $scope.entity={tbGoodsDesc:{itemImages:[],specificationItems:[] } };//定義頁面實體結構
	$scope.add_image_entity=function () {
		$scope.entity.tbGoodsDesc.itemImages.push($scope.image_entity);
    }

 

(2)修改上傳窗口的保存按鈕

<button class="btn btn-success" ng-click="add_image_entity()" data-dismiss="modal" aria-hidden="true">保存</button>

(3)遍歷圖片列表

<tr ng-repeat="pojo in entity.goodsDesc.itemImages">

     <td>{{pojo.color}}</td>

     <td><img alt="" src="{{pojo.url}}" width="100px" height="100px"></td>

    <td><button type="button" class="btn btn-default" title="刪除" ><i class="fa fa-trash-o"></i> 刪除</button></td>

</tr>

6.3.4 移除圖片

在goodsController.js增加代碼

//移除圖片
    $scope.remove_image_entity=function (index) {
        $scope.entity.tbGoodsDesc.itemImages.splice(index,1);
    }

 

修改列表中的刪除按鈕

<button type="button" class="btn btn-default" title="刪除" ng-click="remove_image_entity($index)"><i class="fa fa-trash-o"></i> 刪除</button>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章