axios 传递图片以及后台接收图片
首先在main.js里面导入 axios,然后进行全局挂载,Vue.prototype.$axios = axios这样,在项目中的任何一个位置都能通过this.$axios({}) 去调用了。如:调用登录接口this.$axios({method: "post",url: "/shiro/sys/login",data: {username: this.username,password: th
首先在main.js里面导入 axios,然后进行全局挂载,Vue.prototype.$axios = axios
同时导入 ElementUI
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
Vue.use(ElementUI);
这样,在项目中的任何一个位置都能通过
this.$axios({}) 去调用了。
如:调用登录接口
this.$axios({
method: "post",
url: "/shiro/sys/login",
data: {
username: this.username,
password: this.password
}
}).then(result => {
})
注释:我这里在 vue.config.js 配置了跨域,所以 url 访问到 "/shiro/sys/login 即可。
devServer: {
open: true,//自动打开浏览器
host: 'localhost',//'0.0.0.0' ip地址
port: 8080,
https: false,//false关闭https,true为开启
//以上的ip和端口是我们本机的;下面为需要跨域的
// 讲解博客 https://www.jianshu.com/p/5ef2b17f9b25
proxy: { //配置跨域
'/shiro': {
target: 'http://localhost:9090/shiro/', //这里后台的地址模拟的;应该填写你们真实的后台接口
ws: true,
changOrigin: true, //允许跨域
pathRewrite: {
'^/shiro': '' //请求的时候使用这个api就可以
}
}
}
// 当在$axios 访问 /shiro/sys/login 时,先会把 target 字段加上 ,变为
// http://localhost:9090/shiro/shiro/sys/login,然后在pathRewrite 里把 /shiro 换为 ''
// 变为 http://localhost:9090/shiro/sys/login
},
登录接口 "/shiro/sys/login " 对应的后台接口为:
/**
* 登录
*/
@ApiOperation(value = "登陆", notes = "参数:用户名 密码")
@PostMapping("/sys/login")
public Map<String, Object> login(@RequestBody @Validated LoginDTO loginDTO, BindingResult bindingResult,HttpServletRequest request) {
Map<String, Object> result = new HashMap<>();
if (bindingResult.hasErrors()) {
result.put("status", 400);
result.put("msg", bindingResult.getFieldError().getDefaultMessage());
return result;
}
String username = loginDTO.getUsername();
String password = loginDTO.getPassword();
//用户信息
User user = shiroService.findByUsername(username);
//账号不存在、密码错误
if (user == null || !user.getPassword().equals(password)) {
result.put("status", 400);
result.put("msg", "账号或密码有误");
} else {
//生成token,并保存到数据库
result = shiroService.createToken(user.getUserId());
result.put("status", 200);
result.put("msg", "登陆成功");
}
return result;
}
后台接口中 @RequestBody 把前端传递过来的 json 封装到 LoginDTO 类里。
下面解释:
教程:https://www.runoob.com/vue2/vuejs-ajax-axios.html
因为:axios 会默认序列化 JavaScript 对象为 JSON。 如果想使用 application/x-www-form-urlencoded 格式,你可以使用下面的配置。
import qs from 'qs';
const data = { 'bar': 123 };
const options = {
method: 'POST',
headers: { 'content-type': 'application/x-www-form-urlencoded' },
data: qs.stringify(data),
url,
};
axios(options);
所以,前端传递过来的数据从 LoginDTO 对象里面获取即可。
再如:上传图片
用ElementUI写一个上传图片的div
<el-form :label-position="labelPosition" :model="ruleForm" status-icon ref="ruleForm"
label-width="70px" class="demo-ruleForm">
<el-form-item label="设备外形图:" label-width="130px">
<el-upload
action="string"
:auto-upload="false"
list-type="picture-card"
:on-preview="handlePictureCardPreview"
:on-remove="handleRemovePlan"
:file-list="picture"
:on-change="OnChangeOutLookPlan"
>
<i class="el-icon-plus"></i>
</el-upload>
</el-form-item>
</el-form>
定义初始化数据
labelPosition: 'left',
// 图片上传相关
dialogVisible: true,
dialogImageUrl: 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fa4.att.hudong.com%2F27%2F67%2F01300000921826141299672233506.jpg&refer=http%3A%2F%2Fa4.att.hudong.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1614780040&t=335e293322bac198f2af7379a03a52f6',
planBool:false,
picture: [],
ruleForm: {
name: '',
deviceType: '',
natureOfPoint: '',
project: '',
progress: '',
location: ''
},
param: new FormData(), // 上传数据用这个
<el-upload
组件里面绑定的方法
OnChangeOutLookPlan(file, fileList) {
console.log(fileList)
this.picture = []
this.picture.push(file)
},
handleRemovePlan() {
this.planBool = true
this.picture = []
},
handlePictureCardPreview(file) {
this.dialogImageUrl = file.url;
this.dialogVisible = true;
},
绑定一个按钮,绑定 testPictureUpload 方法
<el-row>
<el-button type="primary" @click="testPictureUpload">testPictureUpload</el-button>
</el-row>
testPictureUpload 方法体
// 测试图片上传
testPictureUpload() {
// 设置数据, 后台用这个接收 @RequestParam("txt") String txt
this.param.set("txt",'66666')
for (var i = 0; i < this.picture.length; i++) {
/**
* 设置数据, 后台接收方式一: @RequestParam("picture") MultipartFile picture
* 后台接收方式二: HttpServletRequest request
* MultipartHttpServletRequest request1 = (MultipartHttpServletRequest) request;
* Map<String, MultipartFile> fileMap = request1.getFileMap();
* MultipartFile pictures = fileMap.get("picture");
* System.out.println(pictures);
*/
this.param.set('picture', this.picture[i].raw);
}
var arr = []
this.param.forEach(function (value) {
arr.push(value)
});
var lastArr = arr
var data = this.param
console.log(lastArr)
this.$axios({
method: "POST",
url: "/shiro/testPictureUpload",
data:data,
headers: {
token: this.token,
'Content-Type': 'multipart/form-data' // 传递图片 headers 里得这样写
}
}).then(res =>{
console.log(res)
this.showMsg(res);
})
},
对应的后台接口
@RequiresPermissions({"save"}) // 意思是,当前登录的用户得有save权限才能使用该接口
@PostMapping("/testPictureUpload")
public Map<String, Object> testPictureUpload(@RequestHeader("token") String token,
@RequestParam("txt") String txt,
@RequestParam("picture") MultipartFile picture,
HttpServletRequest request) {
MultipartHttpServletRequest request1 = (MultipartHttpServletRequest) request;
Map<String, MultipartFile> fileMap = request1.getFileMap();
MultipartFile pictures = fileMap.get("picture");
System.out.println(" 用这个 HttpServletRequest 接收图片: " + pictures);
System.out.println("用这个 @RequestParam MultipartFile 接收图片: " + picture);
System.out.println("testPictureUpload");
Map<String, Object>map = new HashMap<>();
map.put("status", 200);
map.put("msg","当前用户有testPictureUpload权利");
return map;
}
通过 @RequestParam(“picture”) MultipartFile picture, 这个可以直接获取到传递过来的图片。当然,通过 HttpServletRequest request 这个也可以。如下:
MultipartHttpServletRequest request1 = (MultipartHttpServletRequest) request;
Map<String, MultipartFile> fileMap = request1.getFileMap();
MultipartFile pictures = fileMap.get("picture");
System.out.println(" 用这个 HttpServletRequest 接收图片: " + pictures);
下面是介绍如何把图片存入本地磁盘,
String filePath = "file"; // 存储图片的文件夹名字
String resultUrl = FileUtils.saveFile(picture, filePath);
String picturepath = resultUrl.split("@")[0]; // 最后存储在数据库中的图片地址,再前端直接访问即可显示
String pictureFilePath = resultUrl.split("@")[1]; // 文件在磁盘中的路径位置
// 把 picturepath 和 pictureFilePath 等路径存入数据库即可
单纯的保存图片到本地文件夹
public static String saveFile(MultipartFile file,String filePath) throws Exception {
if (file == null || file.isEmpty() || filePath ==null || filePath.isEmpty()) {
return "";
}
File target = new File(filePath);
if (!target.isDirectory()) {
target.mkdirs();
}
System.out.println("System.currentTimeMillis()"+System.currentTimeMillis());
String originalFilename = System.currentTimeMillis() + "_" + file.getOriginalFilename();
// MessageDigest md = MessageDigest.getInstance("MD5");
// md.update(file.getBytes());
String fileName = originalFilename;
File file1 = new File(target.getPath() + "/" + fileName);
Files.write(Paths.get(file1.toURI()), file.getBytes(), StandardOpenOption.CREATE_NEW);
System.out.println(Paths.get(file1.toURI()));
// return "http://localhost:8080/mall/admin/product/img/" + fileName;
// return Paths.get(file1.toURI()).toString();
// return "http://localhost:8086/images/"+ originalFilename;// 最后存储在数据库中的地址
// 最后存储在数据库中的图片地址,再前端直接访问即可显示
// String picturepath = "http://" + getCurrentIp() + ":8086/images/" + originalFilename;
String picturepath = "/images/" + originalFilename;
// 文件在磁盘中的路径位置 TODO 不能使用全路径,回头改为相对路径
String pictureFilePath = Paths.get(file1.toURI()).toString();
String pictureFinalFilePath = "\\file"+pictureFilePath.split("file")[1];
return picturepath +"@"+ pictureFinalFilePath;
}
更多推荐
所有评论(0)