vue代码
<!-- 菜单导入对话框 -->
<el-dialog :title="upload.title" :visible.sync="upload.open" :close-on-click-modal="false" width="400px" append-to-body>
<el-upload
ref="upload"
:limit="1"
:headers="upload.headers"
:action="upload.url"
:disabled="upload.isUploading"
:on-progress="handleFileUploadProgress"
:on-success="handleFileSuccess"
:auto-upload="false"
:on-change="changeUpload"
:file-list="fileUploadList"
:on-exceed="fileUploadExceed"
drag
>
<i class="el-icon-upload"></i>
<div class="el-upload__text">
将文件拖到此处,或
<em>点击上传</em>
</div>
<div class="el-upload__tip" slot="tip">
<!-- <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据 -->
<el-link type="info" style="font-size:12px" @click="importTemplate" v-hasPermi="['system:menu:export']">下载模板</el-link>
</div>
<div class="el-upload__tip" style="color:red" slot="tip">提示:仅允许导入“xls”或“xlsx”格式文件!</div>
</el-upload>
<div slot="footer" class="dialog-footer">
<el-button type="primary" @click="submitFileForm" :disabled="submitFileBtnDisabled">确 定</el-button>
<el-button @click="upload.open = false">取 消</el-button>
</div>
</el-dialog>
// 提交上传文件
submitFileForm() {
let files = this.$refs.upload.uploadFiles
if(files.length == 0) {
this.msgError('请选择文件')
return
}
// this.$refs.upload.submit();
this.submitFileBtnDisabled = true;
let formData = new FormData()
formData.append('file', this.$refs.upload.uploadFiles[0].raw)
exportExcel(formData).then((res)=>{
this.submitFileBtnDisabled = false;
if (res.type == 'application/json') {
console.log(res)
const reader = new FileReader();
reader.readAsText(res, 'utf-8');
reader.onload = () => {
let msg = JSON.parse(reader.result).message;
let status = JSON.parse(reader.result).status;
if(status == '200') {
// 导入成功
this.msgSuccess(msg);
this.handleFileSuccess();
}else{
//处理报错信息 JSON.parse(reader.result)拿到报错信息
this.msgError(msg);
}
};
return;
}else{
// 导入信息有错误
//创建一个隐藏的a连接,
const link = document.createElement('a');
let blob = new Blob([res], {type: 'application/vnd.ms-excel'});
link.style.display = 'none';
//设置连接
link.href = URL.createObjectURL(blob);
link.download = `menu_${new Date().getTime()}.xlsx`; //你文件定义的名称
document.body.appendChild(link);
//模拟点击事件
link.click();
}
}).catch(() => {
this.submitFileBtnDisabled = false;
})
}
引入的js
// 导入提交
export function exportExcel(formData) {
return request({
url: '/system/menu/import',
headers: {
'Content-Type': 'multipart/form-data'
},
method: 'post',
responseType: 'blob',
data: formData,
timeout: 300000
})
}
springboot后端代码
// controller
@PreAuthorize("@ss.hasPermi('system:menu:import')")
@Log(title = "菜单管理", businessType = BusinessType.IMPORT)
@PostMapping("/import")
public void importMenu(@RequestParam("file") MultipartFile file, HttpServletResponse response) throws Exception {
// 导入处理
R<List<MenuExcelData>> handlerResult = menuImportService.handlerData(file);
logger.info("handlerResult:{}--{}", handlerResult.getCode(), handlerResult.getMsg());
if (handlerResult.getCode() != R.SUCCESS) {
if (null != handlerResult.getData()) {
ResponseUtil.excel(response, ModuleTypeEnum.MENU.getName(), MenuExcelData.class, handlerResult.getData());
} else {
String msg = StringUtils.isNotEmpty(handlerResult.getMsg()) ? handlerResult.getMsg() : "导入异常";
ResponseUtil.print(response, "500", msg);
}
} else {
ResponseUtil.print(response, "200", "导入完成");
}
}
回复工具类
package com.ruoyi.system.utils;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.util.MapUtils;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.fastjson.JSON;
import com.ruoyi.common.core.utils.ServletUtils;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
/**
* @description :请求返回工具类
*/
public class ResponseUtil {
/**
* description 打印返回json
*
* @param response 返回
* @param status 状态
* @param message 消息
**/
public static void print(HttpServletResponse response, String status, String message) {
Map<String, String> map = MapUtils.newHashMap();
map.put("status", status);
map.put("message", message);
ServletUtils.renderString(response, JSON.toJSONString(map));
}
/**
* description 返回excel
*
* @param response 返回请求
* @param moduleName 模块名称
* @param clazz 类参数
* @param errorList 错误列表
**/
public static <T> void excel(HttpServletResponse response, String moduleName, Class<?> clazz, List<T> errorList) throws Exception {
response.setContentType("application/octet-stream");
response.setCharacterEncoding("utf-8");
// 这里URLEncoder.encode可以防止中文乱码
String fileName = URLEncoder.encode(moduleName + System.currentTimeMillis(), "UTF-8").replaceAll("\\+", "%20");
response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
EasyExcel.write(response.getOutputStream(), clazz).sheet(moduleName).doWrite(errorList);
response.flushBuffer();
}
/**
* description 多个sheet返回
*
* @param response 返回请求
* @param sheetNames sheet名称
* @param clazz 类参数
* @param errorList 错误列表
**/
public static void excel(HttpServletResponse response, String[] sheetNames, Class<?>[] clazz, Map<String, List<?>> errorList) throws Exception {
response.setContentType("application/octet-stream");
response.setCharacterEncoding("utf-8");
// 这里URLEncoder.encode可以防止中文乱码
String fileName = URLEncoder.encode("Error_" + System.currentTimeMillis(), "UTF-8").replaceAll("\\+", "%20");
response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
try (ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).build()) {
for (int i = 0; i < clazz.length; i++) {
Class<?> aClass = clazz[i];
WriteSheet writeMenuSheet = EasyExcel.writerSheet(sheetNames[i]).head(aClass).build();
excelWriter.write(errorList.get(aClass.getName()), writeMenuSheet);
}
}
response.flushBuffer();
}
/**
* description 返回模板
*
* @param response 返回
* @param tempPathName 模板路径名
* @param sheetName 返回模板修改
* @param clazz 数据类型
* @param dataList 数据
**/
public static <T> void tempFile(HttpServletResponse response, String tempPathName, String sheetName, Class<?> clazz, List<T> dataList) throws Exception {
response.setContentType("application/octet-stream");
response.setCharacterEncoding("utf-8");
// 这里URLEncoder.encode可以防止中文乱码
String fileName = URLEncoder.encode("temp" + System.currentTimeMillis(), "UTF-8").replaceAll("\\+", "%20");
response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
EasyExcel.write(response.getOutputStream(), clazz).withTemplate(EasyExcelUtil.readFileInputStream(tempPathName)).sheet(sheetName).doWrite(dataList);
response.flushBuffer();
}
/**
* description 返回模板
*
* @param response 返回
* @param tempPathName 模板路径名
**/
public static <T> void tempFile(HttpServletResponse response, String tempPathName) throws Exception {
response.setContentType("application/octet-stream");
response.setCharacterEncoding("utf-8");
// 这里URLEncoder.encode可以防止中文乱码
String fileName = URLEncoder.encode("temp" + System.currentTimeMillis(), "UTF-8").replaceAll("\\+", "%20");
response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
ExcelWriter build = EasyExcel.write(response.getOutputStream()).withTemplate(EasyExcelUtil.readFileInputStream(tempPathName)).build();
build.finish();
response.flushBuffer();
}
}
// easyexcel工具类
package com.ruoyi.system.utils;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.system.domain.imports.UserAuthorityExcelData;
import org.springframework.util.StringUtils;
import java.io.File;
import java.io.InputStream;
import java.util.List;
import java.util.Objects;
/**
* @description :导入导出工具类
*/
public class EasyExcelUtil {
/**
* description 获取代码路径
*
* @return java.lang.String
**/
public static String getPath() {
return Objects.requireNonNull(EasyExcelUtil.class.getResource("/")).getPath();
}
/**
* description 获取文件
*
* @param pathName 文件名称
* @return java.io.File
**/
public static File readFile(String pathName) {
return new File(getPath() + pathName);
}
/**
* description 返回文件流
*
* @param resourceFile
* @return java.io.InputStream
**/
public static InputStream readFileInputStream(String resourceFile) {
return EasyExcelUtil.class.getResourceAsStream(resourceFile);
}
/**
* description 登录账号重复统一处理
*
* @param e 异常
* @return com.ruoyi.common.core.domain.R<java.util.List<?>>
**/
public static <T> R<List<T>> illegalStateExceptionHandler(Exception e) {
if (e instanceof IllegalStateException) {
String exceptionMessage = e.getMessage();
if (!StringUtils.isEmpty(exceptionMessage)) {
int duplicateUserId = exceptionMessage.indexOf("userName:");
if (duplicateUserId >= 0) {
return R.fail("登录账号:" + exceptionMessage.substring(duplicateUserId + "userName:".length()) + " 数据库重复请核查!");
}
}
}
return R.fail("导入异常");
}
}
标签:VUE,return,springboot,demo,param,public,import,response,String
From: https://www.cnblogs.com/stubborn-dude/p/17078456.html