6.3 前端代码6.3.1 服务层
(1)在 pinyougou-shop-web 工程创建 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:"../upload.do", data: formData,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,itemCa tService,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>