springBoot 上傳 下載 刪除
阿新 • • 發佈:2018-12-06
吧東西整合了一下
包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