文章目录
注意点
需要安装lombok插件,引入lombok依赖,还有一些ResultUtil;,vo类改成自己的就好
- 后端
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;
/**
*/
@RestController
@Slf4j
@RequestMapping("/file")
@CrossOrigin
public class FileController {
private String bucket="D://opt/bucket";
@SneakyThrows
@PostMapping("/upload")
public String upload(HttpServletRequest request, @RequestParam("file") MultipartFile file) {
// String xxx = request.getParameter("xxx");
//获取所需参数,再进行数据库相关操作
String originalFilename = file.getOriginalFilename();
String uniFileName = UUID.randomUUID().toString();
File file1 = new File(bucket);
if (!file1.exists()) {
if (file1.mkdirs()) {
log.info("makedir success, dir path{}", bucket);
} else {
log.error("makedir error, dir path{}", bucket);
}
}
File dest = new File(bucket +"/"+ uniFileName);
file.transferTo(dest);
//originalFilename存库就好了,uniFileName文件下载时需要传递的参数
return uniFileName;
}
@SneakyThrows
@GetMapping("/download")
public void upload(HttpServletResponse response, String uniFileName) {
String s = bucket + "/" + uniFileName;
byte[] bytes = getBytes(s);
response.addHeader("Accept-Ranges", "bytes");
response.setStatus(200);
response.setContentType("application/octet-stream");
//从数据库里面查到getOriginalFileName
response.addHeader("Content-disposition", "attachment;filename="
+ new String("blog.png".getBytes("UTF-8"), "ISO-8859-1"));
response.getOutputStream().write(bytes);
}
/**
* 删除的话就是删除表记录就行,没必要进行物理删除
* @param fileId
* @return
*/
@SneakyThrows
@GetMapping("/delete/{fileId}")
public String delete(@PathVariable(name = "fileId") String fileId) {
return "success";
}
public byte[] getBytes(String filePath) {
FileInputStream fis = null;
ByteArrayOutputStream bos = null;
byte[] buffer = null;
try {
File file = new File(filePath);
fis = new FileInputStream(file);
bos = new ByteArrayOutputStream(1024);
byte[] b = new byte[1024];
int n;
while ((n = fis.read(b)) != -1) {
bos.write(b, 0, n);
}
buffer = bos.toByteArray();
} catch (FileNotFoundException e) {
log.error("" + e);
} catch (IOException e) {
log.error("" + e);
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
log.error("close stream error");
}
}
if (bos != null) {
try {
bos.close();
} catch (IOException e) {
log.error("close stream error");
}
}
}
return buffer;
}
}
- 前端
<form method="post" id="file" action="" enctype="multipart/form-data">
<input type="file" style="opacity: 0;width: 0px;height: 0px" onchange="uploadFun(this.files[0])" name="file" id="clickUpload">
<input type="button" value="" onclick="alertdim('aa')" placeholder="点击上传文件"/>
</form>
<script>
function alertdim(data) {
$("#clickUpload").click();
}
function uploadFun(data){
$("#info").val(data.name);
var formData = new FormData();
formData.append("file",data);
// formData.append("zfID",$("#xxx").val)
if("undefined" != typeof(data) && data != null && data != ""){
$.ajax({
url:'/file/upload',
type:'POST',
data:formData,
async: false,
cache: false,
contentType: false, //不设置内容类型
processData: false, //不处理数据
success:function(res){
alert(res.message);
},
error:function(){
alert("上传失败!");
}
})
}else {
alert("选择的文件无效!请重新选择");
}
// alert(data+"-------上传")
}
</script>
<a onclick="alertdim(\'e7bf6a2d-b999-4653-aae8-93dae782c812\')" >下载</a>
<script>
//文件下载
function alertdim(data){
$.ajax({
url:"/file/download?uniFileName="+data,
method:"get",
// data : {
// employeeId:$("#download-employeeId").val(),
// },
success: function(res) {
// const data = res
// debugger
// 将二进制文件转化为可访问的url
var data = new Blob([res],{type:"application/octet-stream"});
var url = window.URL.createObjectURL(data);
// let url = URL.createObjectURL(data);
// let url = window.URL.createObjectURL(data)
var a = document.createElement('a')
document.body.appendChild(a)
a.href = url
a.download = 'blog.png'
a.click() // 模拟点击下载
window.URL.revokeObjectURL(url)
}
})
alert(data+"-------下载")
}
</script>
更加完整的前端的可以参考【多图上传原理:每选择一张图片就会发起一次请求】
<el-form-item label="图片上传">
<el-upload
:on-success="onUploadSuccess"
:before-upload="beforeUpload"
:on-preview="onUploadPreview"
:on-remove="onUploadRemove"
:multiple="true"
:action="'api/file/upload'"
class="upload-demo"
list-type="picture-card">
<i class="el-icon-plus"/>
<div slot="tip" class="el-upload__tip">只能上传jpg/png/gif文件,且不超过2MB</div>
</el-upload>
</el-form-item>
methods: {
// 文件上传限制条件
beforeUpload(file) {
const isJPG = file.type === 'image/jpeg'
const isPNG = file.type === 'image/png'
const isGIF = file.type === 'image/gif'
const isLt2M = file.size / 1024 / 1024 < 2
if (!isJPG && !isPNG && !isGIF) {
this.$message.error('上传头像图片只能是 JPG、PNG 或 GIF 格式!')
return false
}
if (!isLt2M) {
this.$message.error('上传头像图片大小不能超过 2MB!')
return false
}
return true
},
// 上传图片成功的回调
onUploadSuccess(res, file) {
// alert("success======")
// let aa=res
// let bb=file
// debugger
// 填充上传文件列表
let cc=res;
let bb=file;
debugger
this.spuForm.spuImageList.push({
imgName: file.name,
imgUrl: file.response
})
},
// 上传的文件预览
onUploadPreview(file) {
this.dialogImageUrl = file.url
this.dialogImageVisible = true
},
// 删除上传的文件
onUploadRemove(file, fileList) {
this.spuForm.spuImageList = []
fileList.forEach(file => {
this.spuForm.spuImageList.push({
imgName: file.name,
imgUrl: file.response
})
})
}
}