文件上传
后端
Controller
package com.ruoyi.system.controller;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.UploadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.xml.ws.soap.Addressing;
@RestController
@RequestMapping("/system/upload")
public class UploadController extends BaseController {
@Autowired
private UploadUtil uploadUtil;
@PostMapping(value = "/file")
public AjaxResult uploadImage(@RequestParam("file") MultipartFile files[]) throws Exception {
return uploadUtil.uploadImages(files);
}
}
Util
package com.ruoyi.common.utils;
import com.ruoyi.common.core.domain.AjaxResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.util.ArrayList;
@Component
public class UploadUtil {
@Value("${file.location}")
private String baseUrl;
/**
* 文件上传
* 获取文件名称,把文件存储到D:\picturePath路径下
* @param files
* @return
* @throws Exception
*/
public AjaxResult uploadImages(MultipartFile files[]) throws Exception {
String url;
try {
ArrayList<String> urlList = new ArrayList<>();;
for (int i = 0; i < files.length; i++) {
MultipartFile multipartFile = files[i];
String fileName = multipartFile.getOriginalFilename();
String realPath = baseUrl;
System.out.println("realPath==>" + realPath);
//创建存放的目录
File dir = new File(realPath);
if (!dir.exists()) {
dir.mkdir();
}
File file = new File(realPath, fileName);
multipartFile.transferTo(file);
url = "http://localhost:8080/dev-api/file/" + fileName;
System.out.println("url==>" + url);
urlList.add(url);
}
return new AjaxResult(200, "文件传送成功", urlList);
} catch (Exception e) {
return new AjaxResult(500, "文件传送失败", null);
//return new CommonResult(2001, "数据库执行有异常", null);
}
// return new CommonResult(200, "添加成功", url);
}
}
AjaxResult
package com.ruoyi.common.core.domain;
import java.util.HashMap;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.utils.StringUtils;
/**
* 操作消息提醒
*
* @author ruoyi
*/
public class AjaxResult extends HashMap<String, Object>
{
private static final long serialVersionUID = 1L;
/** 状态码 */
public static final String CODE_TAG = "code";
/** 返回内容 */
public static final String MSG_TAG = "msg";
/** 数据对象 */
public static final String DATA_TAG = "data";
/**
* 初始化一个新创建的 AjaxResult 对象,使其表示一个空消息。
*/
public AjaxResult()
{
}
/**
* 初始化一个新创建的 AjaxResult 对象
*
* @param code 状态码
* @param msg 返回内容
*/
public AjaxResult(int code, String msg)
{
super.put(CODE_TAG, code);
super.put(MSG_TAG, msg);
}
/**
* 初始化一个新创建的 AjaxResult 对象
*
* @param code 状态码
* @param msg 返回内容
* @param data 数据对象
*/
public AjaxResult(int code, String msg, Object data)
{
super.put(CODE_TAG, code);
super.put(MSG_TAG, msg);
if (StringUtils.isNotNull(data))
{
super.put(DATA_TAG, data);
}
}
/**
* 返回成功消息
*
* @return 成功消息
*/
public static AjaxResult success()
{
return AjaxResult.success("操作成功");
}
/**
* 返回成功数据
*
* @return 成功消息
*/
public static AjaxResult success(Object data)
{
return AjaxResult.success("操作成功", data);
}
/**
* 返回成功消息
*
* @param msg 返回内容
* @return 成功消息
*/
public static AjaxResult success(String msg)
{
return AjaxResult.success(msg, null);
}
/**
* 返回成功消息
*
* @param msg 返回内容
* @param data 数据对象
* @return 成功消息
*/
public static AjaxResult success(String msg, Object data)
{
return new AjaxResult(HttpStatus.SUCCESS, msg, data);
}
/**
* 返回错误消息
*
* @return
*/
public static AjaxResult error()
{
return AjaxResult.error("操作失败");
}
/**
* 返回错误消息
*
* @param msg 返回内容
* @return 警告消息
*/
public static AjaxResult error(String msg)
{
return AjaxResult.error(msg, null);
}
/**
* 返回错误消息
*
* @param msg 返回内容
* @param data 数据对象
* @return 警告消息
*/
public static AjaxResult error(String msg, Object data)
{
return new AjaxResult(HttpStatus.ERROR, msg, data);
}
/**
* 返回错误消息
*
* @param code 状态码
* @param msg 返回内容
* @return 警告消息
*/
public static AjaxResult error(int code, String msg)
{
return new AjaxResult(code, msg, null);
}
/**
* 方便链式调用
*
* @param key 键
* @param value 值
* @return 数据对象
*/
@Override
public AjaxResult put(String key, Object value)
{
super.put(key, value);
return this;
}
}
前端
Vue
<el-upload
class="upload-demo"
drag
action="#"
:http-request="requestUpload"
:on-change="uploadFiles"
multiple>
<i class="el-icon-upload"></i>
<div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
<div class="el-upload__tip" slot="tip">只能上传jpg/png文件,且不超过500kb</div>
</el-upload>
Js
// 覆盖默认的上传行为
requestUpload() {
},
/**
* 上传文件成功的勾子函数,文件上传成功后会调用
* @param res 返回结果,包含code/msg/data信息等
* @constructor
*/
uploadFiles(file){
let formData = new FormData();
console.log(file)
formData.append("file", file.raw);
uploadFile(formData).then(res => {
let list = res.data[0].split("/")
this.form.fileUrl = res.data[0]
this.form.fileName = list[list.length-1]
});
},
// 上传文件
export function uploadFile(data) {
return request({
url: '/system/upload/file',
method: 'post',
data: data
})
}
文件下载
后端
Controller
/**
* 下载文件
* @param request
* @param response
* @throws ServletException
* @throws IOException
* @throws IOException
*/
@RequestMapping("/download")
public void downloadFile(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, IOException {
// TODO Auto-generated method stub
//获得请求文件名
String filename = request.getParameter("filename");
System.out.println(filename);
//设置文件MIME类型
response.setContentType("application/download;utf-8");
//设置Content-Disposition
response.setHeader("Content-Disposition", "attachment;filename="+new String(filename.getBytes("utf-8"), "iso-8859-1"));
//读取目标文件,通过response将目标文件写到客户端
//获取目标文件的绝对路径
String fullFileName = "D:\\picturePath\\"+filename;
//System.out.println(fullFileName);
//读取文件
InputStream in = new FileInputStream(fullFileName);
OutputStream out = response.getOutputStream();
//写文件
int b;
while((b=in.read())!= -1)
{
out.write(b);
}
in.close();
out.close();
}
前端
Vue
<template slot-scope="scope">
<el-button type="primary"
size="mini"
@click="downLoadFile(scope.row.fileName)"
class="table-inner-button"
>下载</el-button>
</template>
Js
/**
* 下载文件
* @param fileName
*/
downLoadFile(fileName){
downloadFile(fileName).then(res=>{
if (!res) {
return
}
let url = window.URL.createObjectURL(new Blob([res]))
let link = document.createElement('a')
link.style.display = 'none'
link.href = url
link.setAttribute('download', fileName)
document.body.appendChild(link)
link.click()
// 释放URL对象所占资源
window.URL.revokeObjectURL(url)
// 用完即删
document.body.removeChild(link)
});
},
// 下载文件
export function downloadFile(query) {
return request({
responseType: 'blob',
url: '/system/file/download?filename='+query,
method: 'get'
})
}
总结
上传文件:用element-ui的组件进行上传,在文件发生改变的时候调用文件上传的接口,然后将返回值进行一些特殊处理。
文件下载:根据文件名称去搜寻文件,把文件以二进制流写入response,把response作为blob资源去下载下来。