后台Controller
package com.example.kemanwu.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
@RestController
public class AddzhangjieController {
//对上传的文件做一个简单的分类,按照时间来
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("/yyyy/MM/dd/");
@PostMapping("/upload")
public Map<String, Object> fileUpload(MultipartFile file, HttpServletRequest req) {
Map<String, Object> resultMap = new HashMap<>();
// 得到上传时的文件名
String originName = file.getOriginalFilename();
if (!originName.endsWith(".pdf")) {
resultMap.put("status", "error");
resultMap.put("msg", "文件类型不对,必须为pdf");
return resultMap;
}
String strFormat = simpleDateFormat.format(new Date());
String realPath = req.getServletContext().getRealPath("/") + strFormat;
String uploadDir = req.getSession().getServletContext().getRealPath("/") + "/upload/" + strFormat;
File folder = new File(realPath);
if (!folder.exists()) {
folder.mkdirs();
}
// 保存文件对象,加上uuid是为了防止文件重名
String strNewFileName = UUID.randomUUID().toString().replaceAll("-", "") + ".pdf";
try {
file.transferTo(new File(folder, strNewFileName));
String strUrl = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + strFormat + strNewFileName;
resultMap.put("status", "success");
resultMap.put("url", strUrl);
} catch (IOException e) {
e.printStackTrace();
resultMap.put("status", "error");
resultMap.put("msg", e.getMessage());
}
return resultMap;
}
}
vue页面
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<!-- import CSS -->
<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
</head>
<body>
<div id="app">
<el-upload
action="/upload"
:on-preview="handlePreview"
multiple
:limit="10"
accept=".pdf">
<el-button size="small" type="primary">点击上传</el-button>
<div slot="tip" class="el-upload__tip">只能上传pdf文件,且不超过100MB</div>
</el-upload>
</div>
</body>
<!-- import Vue before Element -->
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<!-- import JavaScript -->
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
<script>
new Vue({
el: '#app',
methods: {
handlePreview(file) {
console.log(file);
window.open( file.response.url);
}
}
})
</script>
</html>
地址没有写错的地方就是显示404,postman返回的url浏览器也预览不出来显示404,找了好久没找到错啊哭了,我的项目路径是这样的也不会有问题