//vue element-ui组件
<el-upload style=”position: relative;top: -40px;left: 240px;” :show-file-list=”false” :on-success=”onSuccess” :on-error=”onError” :before-upload=”beforeUpload” :on-remove=”handleRemove” action=”/api/upLoadFile” accept=”.json, .txt, .csv, .xls, .xlsx” > <el-button plain type=”primary”>导入</el-button> </el-upload>
//js方法
handleRemove(file, fileList) { }, /** * 上传之前回调函数 */ beforeUpload(file) { console.log(file.name); this.uploaDialog = true; }, /** * 上传失败回调函数 */ onError(err, file, fileList) { this.enabledUploadBtn = false; this.$message({ message: “上传失败”, type: “error” }); }, /** * 上传成功回调函数 */ onSuccess(response, file, fileList) { this.enabledUploadBtn = false; // console.log(response) this.$message({ message: response.msg, type: “info” }); file = []; fileList = []; },
//后台
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
@Controller
public class UploadFile {
private static Logger log = LoggerFactory.getLogger(UploadFile.class);
@RequestMapping(value = “/upLoadFile”, method = RequestMethod.POST, produces = “application/json;charset=utf-8”)
@ResponseBody
public String importFile(@RequestParam(“file”) MultipartFile file,
HttpServletRequest request){
log.info(“importFile()”);
Map<String, String> reMap = new HashMap<>();
if (file.isEmpty()) {
return “文件为空”;
}
// 获取文件名
String fileName = file.getOriginalFilename();
log.info(“上传的文件名为:” + fileName);
// 获取文件的后缀名
String suffixName = fileName.substring(fileName.lastIndexOf(“.”));
log.info(“上传的后缀名为:” + suffixName);
// 文件上传路径 应该改为服务器路径
String filePath = “f:/objdocument/”;
File dest = new File(filePath + fileName);
// 检测是否存在目录
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
try {
file.transferTo(dest);
reMap.put(“msg”, “上传成功”);
} catch (IllegalStateException e) {
log.info(e.toString());
reMap.put(“msg”, “上传失败”);
} catch (IOException e) {
log.info(e.toString());
reMap.put(“msg”, “上传失败”);
}
String str = JsonUtil.map2Json(reMap);
return str;
}
}
application.properties相关配置
spring.http.multipart.enabled=true #默认支持文件上传.
spring.http.multipart.file-size-threshold=0 #支持文件写入磁盘.
spring.http.multipart.location= # 上传文件的临时目录
spring.http.multipart.max-file-size=1Mb # 最大支持文件大小
spring.http.multipart.max-request-size=10Mb # 最大支持请求大小