在毕设项目中使用的是Vue+SpringBoot的框架,前后端分离,前端使用Hubuilder,后端使用IDEA,没有使用Tomcat,上传与下载都在本地。
一、文件上传(前端)
1.使用ElemrntUi自带的el-upload,accept指定上传的文件类型。
<el-upload class="avatar-uploader" action="自己需要上传的网页后端接口,调用的方法(*),也就是后端定义的url"
accept=".jpg,.jpeg,.png,.gif,.JPG,.JPEG" :show-file-list="false"
:on-change="handleLicensePreview" :before-upload="beforeLicenseUpload" :auto-upload="true"
multiple :on-success="handleUploadSuccess">
<img v-if="circleUrl" :src="circleUrl" class="avatar">
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
2.定义上传前的检验操作,比如上传文件的大小等。
beforeLicenseUpload(file) {
const fileSuffix = file.name.substring(file.name.lastIndexOf(".") + 1);
const whiteList = ["jpg", "jpeg", "png", "gif", "JPG", "JPEG"];
if (whiteList.indexOf(fileSuffix) === -1) {
this.$message.error('图片只能为jpg,png,gif类型');
return false;
}
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isLt2M) {
this.$message.error(this.inter.sctpdx + ' 2MB!');
return false;
}
},
3.上传文件
handleLicensePreview(file) {
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isLt2M) {
this.$message.error('图片大小不能超过2MB!');
} else {
let fd = new FormData()//构建实例对象
fd.append('file', file.raw)
// 存储图片,点击确认按钮时统一上传
this.circleUrl = URL.createObjectURL(file.raw);
this.licenseFd = fd//这是上传到后端存储到数据库的文件名,或者可以理解为地址
}
},
二、文件上传(后端)
@RequestMapping("buscode")//这个就是前端那个action所要调用的方法
public String buscode1(@RequestParam("file")MultipartFile file){
if(file.isEmpty()){
return "0";//空文件
}
String filename=file.getOriginalFilename();
File file1=new File("D:\\?\\?\\app2\\src\\assets\\Admin"+"/"+filename);//这个是你上传文件之后所要放置的位置,也可以通过application.yml配置,这里不做过多介绍,filename是文件名字
if (!file1.getParentFile().exists()) {
file1.getParentFile().mkdirs();
}
try {
file.transferTo(file1);
} catch (Exception e) {
throw new RequestMsg("1");
}
return filename;//返回
}
三、通过前端页面进行文件下载
1.前端
前端点击下载的button按钮,调用@click="get()"方法,传入使用的文件名。
get() {
let that = this
this.$axios({
method: 'get',
url: 'http://localhost:8888/bus/downfile?name=' + that.name,
responseType: "arraybuffer"
}).then(function(response) {
let fileName = that.usercode
let url = window.URL.createObjectURL(new Blob([response.data], {
type: "application/octet-stream"
}));
let a = document.createElement('a');
a.style.display = 'none';
a.href = url;
a.setAttribute('download', fileName);
document.body.appendChild(a);
a.click();
url = window.URL.revokeObjectURL(url);
document.body.removeChild(a)
})
},
2.后端
@GetMapping("downfile")
public String filedow1(HttpServletResponse response,@RequestParam("name") String buscode) throws IOException {
System.out.println(buscode);
File file=new File("与上传一样的文件地址"+"/"+buscode);
response.setContentType("application/octet-stream");
response.setCharacterEncoding("UTF-8");//改为UTF-8的标准格式
response.setContentLength((int) file.length());
response.setHeader("Content-Disposition", "attachment;filename=" + name);
byte[] bytes=FileCopyUtils.copyToByteArray(file);
OutputStream os = response.getOutputStream();
os.write(bytes);
return "1";
}
以上就是我做毕设文件的上传与下载。