后端:
package cn.ljy.supplies.controller;
import org.springframework.web.bind.annotation.*;
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 FileUploadController {
SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");
@PostMapping("upload")
public Map<String, Object> fileupload(MultipartFile file, HttpServletRequest req) {
Map<String,Object> result = new HashMap<>();
String originName = file.getOriginalFilename();
if (!originName.endsWith(".pdf")) {
result.put("status","error");
result.put("asg","文件类型不对");
return result;
}
String format = sdf.format(new Date());
String realPath = req.getServletContext().getRealPath("/") +format;
File folder = new File(realPath);
if(!folder.exists()){
folder.mkdirs();
}
String newName = UUID.randomUUID().toString() + ".pdf";
try {
file.transferTo(new File(folder,newName));
String url = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + format + newName;
result.put("status","success");
result.put("url",url);
} catch (IOException e) {
result.put("status","error");
result.put("asg",e.getMessage());
}
return result;
}
}
前端:
<template>
<div>
<el-upload
class="upload-demo"
action=" http://localhost:8080/upload"
:on-success="onSuccess"
:on-preview="handlePreview"
accept=".pdf"
:limit="10">
<el-button size="small" type="primary">点击上传</el-button>
<div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>
</el-upload>
</div>
</template>
<script>
export default {
methods: {
onSuccess(response, file, fileList) {
console.log(response);
console.log(file);
console.log(fileList);
},
handlePreview(file) {
console.log(file)
console.log(file.response.url);
window.open(file.response.url);
}
}
}
</script>
<style>
</style>