SpringBoot+vue前后端分离使用axios进行多文件上传
axios多文件上传、springboot+vue前后端分离上传文件、vue多文件上传。
·
SpringBoot+vue前后端分离使用axios进行多文件上传
vue
<template>
<div class="hello">
<h2>{{ msg }}</h2>
<form>
<input type="file" @change="getFile($event)" multiple="multiple" >
<button class="button button-primary button-pill button-small" @click="submit($event)">提交</button>
</form>
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
name: 'HelloWorld',
msg: '多文件上传',
files:[]
}
},
methods: {
getFile: function (event) {
this.files = event.target.files;
console.log("选择了"+this.files.length+"个文件");
},
submit: function (event) {
//阻止元素发生默认的行为
event.preventDefault();
let formData = new FormData();
for (let i = 0; i < this.files.length; i++) {
formData.append("files", this.files[i]);
}
// 请求路径
var w= 'http://localhost:10010/yp/upload';
let config = {
headers: {
'Content-Type': 'multipart/form-data'
}
}
axios.post(w, formData,config)
.then(function (response) {
console.log("上传成功");
})
.catch(function (error) {
alert("卧槽又BUG");
console.log(error);
});
}
}
}
</script>
application.yaml
限制大小根据情况设置。
prop: upload-folder: 是用来设置文件的存储路径,我这里使用的是绝对路径。如果项目部署则根据情况修改这个路径值。
#文件的限制大小
spring:
servlet:
multipart:
max-file-size: 100MB #文件最大值
max-request-size: 100MB #请求最大值
#文件的存储位置
prop:
upload-folder: F:/S3Project/vue_project/src/assets/upload
java
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
@RestController
public class AddFileMapper {
//时间
SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");
//四舍五入保留两位小数点
DecimalFormat df = new DecimalFormat("######0.00");
//获取application.yaml的属性值
@Value("${prop.upload-folder}")
private String upload_folder;
/**
* 上传文件
* @param files
* @return
*/
@PostMapping("/yp/upload")
public Object singleFileUpload(@RequestParam("files") MultipartFile[] files) {
System.out.println(files.length);
for (MultipartFile file : files) {
try{
String format = sdf.format(new Date());
//路径方式:1、绝对路径
String realPath = upload_folder+format;
System.out.println("存放路径:"+realPath);
File folder = new File(realPath);
if (!folder.exists()) {
folder.mkdirs();
}
String oldName = file.getOriginalFilename();
String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."));
file.transferTo(new File(folder,newName));
String url = "http://localhost:3000/src/assets/upload" + format + newName;
System.out.println("前端访问路径:"+url);
//文件名称
String fileName="/upload" + format + newName;
//文件大小
String fileSize = df.format((file.getSize()/1024))+"kb";
System.out.println("文件名称:"+fileName+"---文件大小"+fileSize);
}catch (Exception e){
return "上传失败";
}
}
return "上传成功";
}
}
更多推荐
已为社区贡献2条内容
所有评论(0)