Spring Boot项目(六):文件的上传和下载功能

踩了很多坑,总结了很多经验才决定写下来,不容易,请各位点点赞,评评论,谢谢。

 

前言:springboot的配置,在这里我就不多说了,翻看我前面的博客就可以了。

一、简单的前端页面代码

<footer>
	<input type="file" @change="getFile()" value="浏览文件" >
	<input type="submit" @click="submitForm()" value="上传" >
</footer>
<br><br>
<input type="submit" @click="download()" value="下载" >

效果图:

二、vue.js代码

三个方法分别对应上面的三个 input

下载的方法里我写死了要下载的文件(呵呵.xls),到时候自己根据文件名下载,或者把文件名存到数据库,下载的时候选择

                        getFile() {
				this.file = event.target.files[0];
			},
			submitForm() {
				let formData = new FormData();
		                formData.append("file", this.file);
				axios.post('upload', formData).then(function(response) {
					alert(response.data);
				})
			},
			download(){
				var str="呵呵.xls";
				window.location.href="download?filename="+str;
			}

三、控制器类

filedir是文件上传和下载的目录位置(上传的文件放在该目录,下载的文件从该目录下载)

package com.demo.controller;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Objects;

import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class FileController {
	
	String filedir="D:\\mwh\\workspace-sts\\file";

	@RequestMapping("/upload")
	@ResponseBody
	public Object upload(@RequestParam(value="file")MultipartFile  file){
		if (Objects.isNull(file) || file.isEmpty()) {
            return "文件为空,请重新上传";
        }
		try {
			byte[] bytes=file.getBytes();
			Path path=Paths.get(filedir+"/"+file.getOriginalFilename());
			//如果没有files文件夹,则创建
            if (!Files.isWritable(path)) {            	
                Files.createDirectories(Paths.get(filedir));
            }
            //文件写入指定路径
            Files.write(path, bytes);
            return "文件上传成功";
		} catch (IOException e) {
			e.printStackTrace();
			return "后端异常";
		}		
	}
	
	@RequestMapping("/download")
	public void download(HttpServletResponse response,@RequestParam(value="filename")String fileName) throws UnsupportedEncodingException{
		File file = new File(filedir+"/"+fileName);
		if (file.exists()) {
			response.setContentType("application/vnd.ms-excel;charset=UTF-8");
			response.addHeader("Content-Disposition", "attachment;fileName=" + java.net.URLEncoder.encode(fileName,"UTF-8"));
			byte[] buffer = new byte[1024];
			FileInputStream fis = null;
			BufferedInputStream bis = null;
			try {
				fis = new FileInputStream(file);
				bis = new BufferedInputStream(fis);
				OutputStream outputStream = response.getOutputStream();
				int i = bis.read(buffer);
				while (i != -1) {
					outputStream.write(buffer);
					i = bis.read(buffer);
				}
			} catch (Exception e) {
					e.printStackTrace();
			} finally {
				if (bis != null) {
					try {
						bis.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				if (fis != null) {
					try {
						fis.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}
			}
	}
}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值