Ideas:
The front end selects a local image and clicks to upload. Controller.js sends an upload request through service.js and returns the packaged data data. The data includes URL: response.data.url and status code response.data.status. The URL is the image's URL, if you want to display it on the page, get the URL directly
The back-end obtains the request from the front-end, uploads the image to the server through the service path and another wave of operations, and encapsulates the status code and URL in the map to return
Total: The front end uses angularJS to upload asynchronously, and the back end uses springmvc's MultipartFile type to receive and put it
in the distributed image server. The server returns the image path and returns the path to the page to echo the image.
front end
page
<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 controller
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 将序列化表单对象中的文件为二进制数据.
*/
Backend dependency
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>
Configuration file upload parser
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>
Controller
Create UploadController under the com.pinyougou.shop.controller package
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;
}
}
Service path configuration file
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 configuration loading application.properties
<!-- 加载属性文件 -->
<context:property-placeholder location="classpath:application.properties"/>
About the project behind is the save reference day06
Click save on the page to jump to the list to display all the pictures, the data in the pictures are encapsulated in picEntity
page
<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);
};
List display page
<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>
Remove picture from list
page
<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);
};