springBoot 上传 下载 删除
程序员文章站
2022-06-02 14:29:55
...
吧东西整合了一下
包id=多个文件上传的统一id 其他方法调用时使用包ID获取数据
html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head th:include="commonHead :: commonHEAD('上传文件测试')"/>
<body>
<button type="button" class="layui-btn" id="test1">
<i class="layui-icon"></i>上传文件
</button>
<button type="button" class="layui-btn" id="btn">提交</button>
<input type="text" id="delid" lay-verify="required" placeholder="输入需要删除文件的ID " autocomplete="off" class="layui-input"/>
<button type="button" class="layui-btn" id="delbtn">删除文件</button>
</body>
<div th:include="onloadJs :: onloadJS"></div>
<script type="text/javascript" th:inline="javascript">
/* <![CDATA[ */
$(function () {
//根据 包ID 获取到这个包里面的文件
$.post("filelist.json",{packageid:123},function (data) {
console.info(data);
});
})
$("#delbtn").click(function () {
//获取到需要删除的文件数据ID
var delid=$("#delid").val();
$.post("del.json",{id:delid},function (data) {
alert(data);
});
});
//上传
layui.use('upload', function(){
var upload = layui.upload;
var packageid = 123;
//执行实例
var uploadInst = upload.render({
elem: '#test1' //绑定元素
,url: 'fileUpload.json' //上传接口
,auto:false
,data:{packageid:packageid}
,bindAction:"#btn"
,multiple:true
,allDone: function(obj){ //当文件全部被提交后,才触发
console.log("文件总数"+obj.total); //得到总文件数
console.log("请求成功的文件数"+obj.successful); //请求成功的文件数
console.log("请求失败的文件数"+obj.aborted); //请求失败的文件数
}
,done: function(res){
//上传完毕回调
console.info("上传完毕回调"+res);
}
,error: function(){
//请求异常回调
}
});
});
/* ]]> */
</script>
</html>
controller
package com.tjr.supervisory.system.controller;
import com.tjr.supervisory.system.aop.Operation;
import com.tjr.supervisory.system.model.TjrFile;
import com.tjr.supervisory.system.model.User;
import com.tjr.supervisory.system.service.FileService;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import java.util.UUID;
/**
* @author zhaojf
* @Title: 上传接口
* @Description: 上传文件统一接口
* @date 2018/8/2210:11
*/
@Controller
@RequestMapping("file")
public class fileController {
Logger log = LoggerFactory.getLogger(this.getClass());
@Autowired
FileService fileService;
// 需要删除的文件路径
String filePath = "D:/test/" ;
@RequestMapping("filetest.htm")
public String fileTestHtm(){
return "filetest";
}
/**
* 实现文件上传
* packageid 包ID
* describe 备注
* */
@RequestMapping("fileUpload.json")
@ResponseBody
@Operation("文件上传")
public String fileUpload(@RequestParam("file") MultipartFile file,
@RequestParam String packageid,
@RequestParam(required = false,defaultValue = "") String describe){
if(file.isEmpty()){
return "false";
}
String uuidname= UUID.randomUUID().toString().replace("-", "").toLowerCase();
String fileName = file.getOriginalFilename();
int size = (int) file.getSize();
log.info(fileName + "-->" + size);
File dest = new File(filePath + uuidname);
//判断文件父目录是否存在
if(!dest.getParentFile().exists()){
dest.getParentFile().mkdir();
}
User user = (User) SecurityUtils.getSubject().getPrincipal();
Integer userid =user.getId();
TjrFile tjrFile = new TjrFile();
//包ID
tjrFile.setPackageid(packageid);
//备注
tjrFile.setDescribe(describe);
//上传用户ID
tjrFile.setPersonalId(userid);
//上传日期 时间戳
tjrFile.setDt1(System.currentTimeMillis());
//文件名
tjrFile.setFilename(fileName);
//路径
tjrFile.setPath(filePath);
//uuidname
tjrFile.setUuidname(uuidname);
try {
fileService.save(tjrFile);
//保存文件
file.transferTo(dest);
return "true";
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "false";
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "false";
}
}
/**
* 实现多文件上传
* 在系统中可以不用,只用单个文件上传就好了,lay机制只会一个一个上传
* */
@RequestMapping(value="multifileUpload.json",method=RequestMethod.POST)
@Operation("多文件上传")
public @ResponseBody String multifileUpload(HttpServletRequest request){
List<MultipartFile> files = ((MultipartHttpServletRequest)request).getFiles("fileName");
if(files.isEmpty()){
return "false";
}
String path = "D:/test" ;
for(MultipartFile file:files){
String fileName = file.getOriginalFilename();
int size = (int) file.getSize();
System.out.println(fileName + "-->" + size);
if(file.isEmpty()){
return "false";
}else{
File dest = new File(path + "/" + fileName);
if(!dest.getParentFile().exists()){ //判断文件父目录是否存在
dest.getParentFile().mkdir();
}
try {
file.transferTo(dest);
}catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "false";
}
}
}
return "true";
}
@RequestMapping("download.htm")
@Operation("文件下载")
public String downLoad(HttpServletResponse response,@RequestParam Integer id){
TjrFile tjrFile = fileService.findOne(id);
//UUID name
String uuidname=tjrFile.getUuidname();
//文件名
String filename= tjrFile.getFilename();
File file = new File(filePath + uuidname);
if(file.exists()){ //判断文件父目录是否存在
response.setContentType("application/force-download");
//修改下载文件的文件名
response.setHeader("Content-Disposition", "attachment;fileName=" + filename);
byte[] buffer = new byte[1024];
FileInputStream fis = null; //文件输入流
BufferedInputStream bis = null;
OutputStream os = null; //输出流
try {
os = response.getOutputStream();
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
int i = bis.read(buffer);
while(i != -1){
os.write(buffer);
i = bis.read(buffer);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
log.info("=========================文件下载" + filename);
try {
bis.close();
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
@PostMapping("del.json")
@ResponseBody
@Operation("文件删除")
public String delfile(@RequestParam Integer id){
TjrFile tjrFile = fileService.findOne(id);
try {
fileService.del(id);
File file = new File(filePath+tjrFile.getUuidname());
if (file.delete()) {
log.info(file.getName() + "is deleted");
return "true";
} else {
log.info("Delete failed.");
return "false";
}
} catch (Exception e) {
log.info("Exception occured");
e.printStackTrace();
return "false";
}
}
@PostMapping("filelist.json")
@ResponseBody
public List<TjrFile> fileList(@RequestParam String packageid){
return fileService.Packageid(packageid);
}
}
service
package com.tjr.supervisory.system.service;
import com.tjr.supervisory.system.model.TjrFile;
import java.util.List;
/**
* @author zhaojf
* @Title: 文件数据库
* @Description: ${todo}
* @date 2018/8/2211:56
*/
public interface FileService {
/**
* 通过个人ID获取到文件
* @param PersonalId 个人ID
* @return
*/
List<TjrFile> PersonalId(Integer PersonalId);
/**
* 通过包ID获取到文件
* @param Packageid
* @return
*/
List<TjrFile> Packageid(String Packageid);
TjrFile findOne(Integer id);
TjrFile save(TjrFile model);
void del(Integer id);
}
service impl
package com.tjr.supervisory.system.service.impl;
import com.tjr.supervisory.system.dao.FileDao;
import com.tjr.supervisory.system.model.TjrFile;
import com.tjr.supervisory.system.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @author zhaojf
* @Title: 文件数据库
* @Description: ${todo}
* @date 2018/8/2214:39
*/
@Service
public class FileServiceImpl implements FileService {
@Autowired
FileDao fileDao;
@Override
public List<TjrFile> PersonalId(Integer PersonalId) {
return fileDao.findByPersonalId(PersonalId);
}
@Override
public List<TjrFile> Packageid(String Packageid) {
return fileDao.findByPackageid(Packageid);
}
@Override
public TjrFile findOne(Integer id) {
return fileDao.findOne(id);
}
@Override
public TjrFile save(TjrFile model) {
return fileDao.save(model);
}
@Override
public void del(Integer id) {
fileDao.delete(id);
}
}
dao
package com.tjr.supervisory.system.dao;
import com.tjr.supervisory.system.model.TjrFile;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
/**
* @author zhaojf
* @Title: 文件上传
* @Description: ${todo}
* @date 2018/8/2211:50
*/
public interface FileDao extends JpaRepository<TjrFile,Integer> {
/**
* 通过个人ID获取到文件
* @param PersonalId 个人ID
* @return
*/
List<TjrFile> findByPersonalId(Integer PersonalId);
/**
* 通过包ID获取到文件
* @param Packageid
* @return
*/
List<TjrFile> findByPackageid(String Packageid);
}
sql
上一篇: OGNL概念和原理详解
下一篇: Struts2之初识ognl