思路:
前端选择本地图片点击上传,controller.js通过service.js发送上传请求,返回封装数据data,该数据中的有URL:response.data.url和状态码response.data.status,该URL就是图片的URL,如果想在页面中显示,就直接获取该URL
后端获取到前端的请求,经过服务路径和其他一波操作把图片上传到服务器,并状态码和URL封装到map中返回
总:前端使用 angularJS 异步上传,后端使用 springmvc 的 MultipartFile 类型来接收,放
到分布式图片服务器中,服务器返回图片路径把路径返回页面回显图片
前端
页面
<table class="table table-bordered table-striped">
<tr>
<td>颜色</td>
<td><input class="form-control"
ng-model="picEntity.color" placeholder="颜色"></td>
</tr>
<tr>
<td>商品图片</td>
<td>
<table>
<tr>
<td>
<input type="file" id="file"/>
<button class="btn btn-primary"
ng-click="uploadFile()"
type="button">上传</button>
</td>
<td><img src="{
{picEntity.url}}"
width="200px" height="200px"></td>
</tr>
</table>
</td>
</tr>
</table>
js控制器
goodsController.js
/**上传图片 */
$scope.uploadFile = function(){
baseService.uploadFile().then(function(response) {
/** 如果上传成功,取出url */
if(response.data.status == 200){
/** 设置图片访问地址 */
$scope.picEntity.url = response.data.url;
}else{
alert("上传失败!");
}
});
};
baseService.js
app.service("baseService", function($http){
/** 文件上传方法 */
this.uploadFile = function(){
/** 创建表单对象 */
var formData = new FormData();
/** 追加需要上传的文件 */
formData.append("file", file.files[0]);
/** 发送异步请求上传文件 */
return $http({
method : 'post', // 请求方式
url : "/upload", // 请求URL
data : formData, // 表单数据
headers : {
'Content-Type' : undefined}, // 请求头
transformRequest : angular.identity // 转换对象
});
};
});
/**
angularjs对于post和get请求默认的Content-Type header 是application/json。通过设置‘Content-Type’: undefined,这样浏览器会帮我们把Content-Type设置为 multipart/form-data.
设置 transformRequest : angular.identity,angularjs transformRequest function 将序列化表单对象中的文件为二进制数据.
*/
后端依赖
pinyougou-shop-web/pom.xml
<!-- commons-fileupload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
</dependency>
<!-- fastdfs-client -->
<dependency>
<groupId>org.csource</groupId>
<artifactId>fastdfs-client</artifactId>
</dependency>
配置文件上传解析器
pinyougou-shop-web/src/main/resources/springmvc.xml
<!-- 配置文件上传解析器 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 设置文件上传默认编码 -->
<property name="defaultEncoding" value="UTF-8"/>
<!-- 设置文件上传大小 2MB: 2*1024*1024 -->
<property name="maxUploadSize" value="2097152"/>
</bean>
控制器
com.pinyougou.shop.controller包下创建UploadController
UploadController.java
@RestController
public class UploadController {
/** 注入文件服务器访问地址 */
@Value("${fileServerUrl}")
private String fileServerUrl;
/** 文件上传 */
@PostMapping("/upload")
public Map<String, Object>
upload(@RequestParam("file")MultipartFile multipartFile) {
Map<String, Object> data = new HashMap<>();
data.put("status", 500);
try {
/** 加载配置文件,产生该文件绝对路径 */
String conf_filename = this.getClass()
.getResource("/fastdfs_client.conf").getPath();
/** 初始化客户端全局对象 */
ClientGlobal.init(conf_filename);
/** 创建存储客户端对象 */
StorageClient storageClient = new StorageClient();
/** 获取原文件名 */
String originalFilename =
multipartFile.getOriginalFilename();
/** 上传文件到FastDFS服务器 */
String[] arr = storageClient
.upload_file(multipartFile.getBytes(),
FilenameUtils.getExtension(originalFilename), null);
/** 拼接返回的 url 和 ip 地址,拼装成完整的 url */
StringBuilder url = new StringBuilder(fileServerUrl);
for (String str : arr){
url.append("/" + str);
}
data.put("status", 200);
data.put("url", url.toString());
} catch (Exception e) {
e.printStackTrace();
}
return data;
}
}
服务路径配置文件
pinyougou-shop-web/src/main/resources/fastdfs_client.conf
# 配置追踪服务器的地址
tracker_server=192.168.12.131:22122
application.properties
# 配置文件服务器的访问地址
fileServerUrl=http://192.168.12.131
springmvc.xml配置加载application.properties
<!-- 加载属性文件 -->
<context:property-placeholder location="classpath:application.properties"/>
关于项目后面是保存参考day06
页面点击保存跳转到列表中显示全部的图片,图片中的数据都封装在picEntity中
页面
<button class="btn btn-success" data-dismiss="modal"
ng-click="addPic()"
aria-hidden="true">保存</button>
goodsController.js
/** 定义数据存储结构 */
$scope.goods = {
goodsDesc : {
itemImages : []}};
/** 添加图片到数组 */
$scope.addPic = function(){
$scope.goods.goodsDesc.itemImages.push($scope.picEntity);
};
列表显示页面
<tr ng-repeat="pic in goods.goodsDesc.itemImages">
<td>{
{pic.color}}</td>
<td><img alt="" src="{
{pic.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>
列表中移除图片
页面
<button type="button" class="btn btn-default" title="删除"
ng-click="removePic($index)">
<i class="fa fa-trash-o"></i> 删除</button>
goodsController.js
/** 数组中移除图片 */
$scope.removePic = function(index){
$scope.goods.goodsDesc.itemImages.splice(index, 1);
};