本帖最后由 我是楠楠 于 2020-5-21 10:48 编辑
【郑州校区】品优购电商系统开发第 5 章 九
6.3 前端代码
6.3.1 服务层
(1)在 pinyougou-shop-web 工程创建 uploadService.js
[AppleScript] 纯文本查看 复制代码 //文件上传服务层
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 中
[AppleScript] 纯文本查看 复制代码 //商品控制层(商家后台)
app.controller('goodsController' ,function($scope,$controller ,goodsService,itemCa
tService,uploadService){
(3)在 goods_edit.html 引入 js
[AppleScript] 纯文本查看 复制代码 <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 编写代码
[AppleScript] 纯文本查看 复制代码 /**
* 上传图片
*/
$scope.uploadFile=function(){
uploadService.uploadFile().success(function(response) {
if(response.success){//如果上传成功,取出 url
$scope.image_entity.url=response.message;//设置文件地址
}else{
alert(response.message);
}
}).error(function() {
alert("上传发生错误");
});
};
(2)修改图片上传窗口,调用上传方法,回显上传图片
[AppleScript] 纯文本查看 复制代码 <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>[/size][/font]<td>
<img src="{{image_entity.url}}" width="200px"
height="200px">
</td>
</tr>
</table>
</td>
</tr>
</table>
[color=#808080][font=Consolas][size=9pt]</div>[/size][/font][/color]
[font=微软雅黑][size=3]
|
|