目录
一.目标概述
这一次项目实施的目的是实现图片的上传和url的生成,因此,主要是前端上传图片代码和后端图片接口的编写。
二.功能设计与实现
1.配置配置文件
其中filepath是路径
filePath=/upload/images
spring.web.resources.static-locations=classpath:static/**spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,file:${filePath}
2.编写后端代码
上传图片后,需要进行接收,同时生成一串数字对图片文件进行重命名,从而进行保存,防止名字重复,最后生成url,传给前端,前端交给im服务器,进行保存,从而实现头像的保存
package com.feixun.feixunshiyan.controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
@RestController
@CrossOrigin
@RequestMapping("/upload")
public class UploadController {
SimpleDateFormat sd = new SimpleDateFormat("yyyy/MM/dd");
@PostMapping("/uploadImg")
public String uploadImg(MultipartFile uploadFile, HttpServletRequest req){
//获取文件名
String fileName = uploadFile.getOriginalFilename();
//获取文件后缀名
String suffixName = fileName.substring(fileName.lastIndexOf("."));
//重新生成文件名
fileName = UUID.randomUUID()+suffixName;
//添加日期目录
String format = sd.format(new Date());
//指定本地文件夹存储图片
String filePath = "/upload/images/"+format+"/";
File file = new File(filePath,fileName);
if (!file.getParentFile().exists()){
file.getParentFile().mkdirs();
}
try {
//将图片保存到static文件夹里
file.createNewFile();
uploadFile.transferTo(new File(filePath+fileName));
return "http://"+"124.221.248.254"+":"+req.getServerPort()+"/"+format+"/"+fileName;
} catch (Exception e) {
e.printStackTrace();
return "false";
}
}
}
3.前端代码
bindAvatarChange:function(){
var me = this;
uni.chooseImage({
count: 1,
sizeType: ['original', 'compressed'],
sourceType: ['album'],
success: function (res) {
me.imgPaths = res.tempFilePaths;
console.log(me.imgPaths);
uni.uploadFile({
url: 'http://124.221.248.254:8081/upload/uploadImg',
filePath: me.imgPaths[0],
name: 'uploadFile',
formData: {
'user': 'test'
},
success: (uploadFileRes) => {
console.log(uploadFileRes);
let promise = tim.updateMyProfile({
avatar: uploadFileRes.data
});
promise.then((imResponse)=> {
console.log(imResponse.data);
}).catch(function(imError) {
console.warn('updateMyProfile error:', imError);
});
}
});
}
});
三.总结
通过这一次项目的实施,完成了图片的传输,为有关图片的上传操作奠定了基础,推动了后续项目的实施。