Java实现多文件上传,下载,模糊搜索

文档管理需求如题。

Entity:

  1. import javax.persistence.Entity;
  2. import javax.persistence.GeneratedValue;
  3. import javax.persistence.GenerationType;
  4. import javax.persistence.Id;
  5. import org.apache.commons.lang3.builder.ToStringBuilder;
  6. @Entity
  7. public class Document {
  8. @Id
  9. @GeneratedValue(strategy = GenerationType.IDENTITY)
  10. public Long id;
  11. public String name;//文件名
  12. public String alias;//别名
  13. public String documentPath;//上传文件(文件存储位置)
  14. public String lable;//标签
  15. public String remark;//备注
  16. //get set方法
  17. }
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import org.apache.commons.lang3.builder.ToStringBuilder;

@Entity
public class Document {

	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	public Long id;
	public String name;//文件名
	public String alias;//别名
	public String documentPath;//上传文件(文件存储位置)
	public String lable;//标签
	public String remark;//备注

	//get set方法
}

Service:

  1. import java.io.*;
  2. import java.lang.reflect.InvocationTargetException;
  3. import java.util.*;
  4. import javax.persistence.*;
  5. import javax.servlet.http.HttpServletRequest;
  6. import javax.servlet.http.HttpServletResponse;
  7. import org.apache.commons.beanutils.BeanUtils;
  8. import org.carrot.domain.Document;
  9. import org.carrot.repository.DocumentDao;
  10. import org.carrot.util.FileUtil;
  11. import org.springframework.beans.factory.annotation.Autowired;
  12. import org.springframework.data.domain.Page;
  13. import org.springframework.data.domain.Pageable;
  14. import org.springframework.data.jpa.domain.Specification;
  15. import org.springframework.stereotype.Service;
  16. import org.springframework.transaction.annotation.Transactional;
  17. import org.springframework.web.multipart.MultipartFile;
  18. import com.google.common.collect.Lists;
  19. import com.google.common.collect.Maps;
  20. @Service
  21. public class DocumentService {
  22. @Autowired
  23. private DocumentDao documentDao;
  24. @Transactional
  25. public List<Document> upload( MultipartFile[] newfiles,Document document,HttpServletRequest request) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
  26. List<Document> list = new ArrayList<Document>();
  27. for (MultipartFile newfile : newfiles) {
  28. Document fileX = new Document();
  29. if (newfile.getSize() > 0) {
  30. document.documentPath = request.getSession().getServletContext().getRealPath("upload/");
  31. document.name = newfile.getOriginalFilename();
  32. BeanUtils.copyProperties(fileX,document);
  33. list.add(fileX);
  34. try {
  35. FileUtil.uploadFile(newfile.getBytes(), document.documentPath, document.name);
  36. documentDao.save(fileX);
  37. } catch (Exception e) {
  38. e.printStackTrace();
  39. }
  40. }
  41. }
  42. return list;
  43. }
  44. @Transactional
  45. public Object download(HttpServletResponse response,HttpServletRequest request,Long id) throws IOException{
  46. Document document = documentDao.findOne(id);
  47. if (document != null) {
  48. //是从"upload\下获取文件 然后下载到C:\\users\\downloads即本机的默认下载的目录
  49. String realPath = request.getSession().getServletContext().getRealPath("upload/");
  50. File file = new File(realPath, document.name);
  51. if (file.exists()) {
  52. response.setContentType("application/force-download");// 设置强制下载不打开
  53. response.addHeader("Content-Disposition","attachment;fileName=" + document.name );// 设置文件名
  54. byte[] buffer = new byte[1024];
  55. FileInputStream fis = null;
  56. BufferedInputStream bis = null;
  57. OutputStream os = null;
  58. try {
  59. fis = new FileInputStream(file);
  60. bis = new BufferedInputStream(fis);
  61. os = response.getOutputStream();
  62. int i = bis.read(buffer);
  63. while (i != -1) {
  64. os.write(buffer, 0, i);
  65. i = bis.read(buffer);
  66. }
  67. } catch (Exception e) {
  68. e.printStackTrace();
  69. }
  70. }
  71. }
  72. return null;
  73. }
  74. @Transactional(readOnly = true)
  75. public Map<String,Object> search( String searchValue, Pageable pageable) {
  76. HashMap<String, Object> maps = Maps.newHashMap();
  77. Page<Document> pageRecharge = documentDao.findAll(new Specification<Document>() {
  78. public Predicate toPredicate(Root<Document> root, CriteriaQuery<?> query, CriteriaBuilder cb) { // 根据条件获取任务列表
  79. //按document类里的字段实现模糊搜索
  80. Path<String> palias = root.get("alias");
  81. Path<String> pname = root.get("name");
  82. Path<String> plable = root.get("lable");
  83. List<Predicate> predicates = Lists.newArrayList();
  84. if (searchValue != null) {
  85. Predicate p1 = cb.like(palias,"%"+searchValue+"%");
  86. Predicate p2 = cb.like(pname,"%"+searchValue+"%");
  87. Predicate p3 = cb.like(plable,"%"+searchValue+"%");
  88. Predicate p = cb.or(p3,cb.or(p1),cb.or(p2));
  89. predicates.add(p);
  90. }
  91. Predicate[] predicateArr = new Predicate[predicates.size()];
  92. query.where(predicates.toArray(predicateArr));
  93. return null;
  94. }
  95. }, pageable);
  96. maps.put("total", pageRecharge.getTotalElements());
  97. maps.put("list", pageRecharge.getContent());
  98. return maps;
  99. }
  100. }
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
import javax.persistence.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.beanutils.BeanUtils;
import org.carrot.domain.Document;
import org.carrot.repository.DocumentDao;
import org.carrot.util.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

@Service
public class DocumentService {
	
	 
	 @Autowired
	 private DocumentDao documentDao;
	 
	 @Transactional
	 public List<Document> upload( MultipartFile[] newfiles,Document document,HttpServletRequest request) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
		 List<Document> list = new ArrayList<Document>();
		 for (MultipartFile newfile : newfiles) {
			 Document fileX = new Document();
		      if (newfile.getSize() > 0) {
		    	  document.documentPath = request.getSession().getServletContext().getRealPath("upload/");
		    	  document.name = newfile.getOriginalFilename();
		    	
		    	  BeanUtils.copyProperties(fileX,document);
		 		  list.add(fileX);
		 		  try {
		               FileUtil.uploadFile(newfile.getBytes(), document.documentPath, document.name);
		               documentDao.save(fileX);
		          } catch (Exception e) {
		         	   e.printStackTrace();
		         }   
		      } 
		    }
         return list;	 
	 }
	 
	 @Transactional
	 public Object download(HttpServletResponse response,HttpServletRequest request,Long id) throws IOException{ 
		 Document document = documentDao.findOne(id);
	     if (document != null) {
	        //是从"upload\下获取文件 然后下载到C:\\users\\downloads即本机的默认下载的目录
	        String realPath =  request.getSession().getServletContext().getRealPath("upload/");
	        File file = new File(realPath, document.name);
	        if (file.exists()) {
	        	response.setContentType("application/force-download");// 设置强制下载不打开
	        	response.addHeader("Content-Disposition","attachment;fileName=" + document.name );// 设置文件名
	        	byte[] buffer = new byte[1024];
	        	FileInputStream fis = null;
	        	BufferedInputStream bis = null;
	        	OutputStream os = null;
	        	try {
	        		fis = new FileInputStream(file);
	        		bis = new BufferedInputStream(fis);
	        		os = response.getOutputStream();
	        		int i = bis.read(buffer);
	        		while (i != -1) {
	        			os.write(buffer, 0, i);
	        			i = bis.read(buffer);
	        		}
	        	} catch (Exception e) {
	        		e.printStackTrace();
	        	} 
	        }
		    }
		return null;
	  }	 
	 
    @Transactional(readOnly = true)
    public Map<String,Object> search( String searchValue, Pageable pageable) {
        HashMap<String, Object> maps = Maps.newHashMap();
        Page<Document> pageRecharge = documentDao.findAll(new Specification<Document>() {
            public Predicate toPredicate(Root<Document> root, CriteriaQuery<?> query, CriteriaBuilder cb) { // 根据条件获取任务列表
                //按document类里的字段实现模糊搜索
                Path<String> palias = root.get("alias");
                Path<String> pname = root.get("name");
                Path<String> plable = root.get("lable");

                List<Predicate> predicates = Lists.newArrayList();
                if (searchValue != null) {
                	Predicate p1 = cb.like(palias,"%"+searchValue+"%");
                	Predicate p2 = cb.like(pname,"%"+searchValue+"%");
                	Predicate p3 = cb.like(plable,"%"+searchValue+"%");
                	Predicate p = cb.or(p3,cb.or(p1),cb.or(p2)); 
                	predicates.add(p);
                } 
                Predicate[] predicateArr = new Predicate[predicates.size()];
                query.where(predicates.toArray(predicateArr));
                return null;
             }
        }, pageable);
        maps.put("total", pageRecharge.getTotalElements());
        maps.put("list", pageRecharge.getContent());
        return maps;
    }	 
}

Dao:

  1. import org.carrot.domain.Document;
  2. import org.springframework.data.domain.Page;
  3. import org.springframework.data.domain.Pageable;
  4. import org.springframework.data.jpa.domain.Specification;
  5. import org.springframework.data.jpa.repository.JpaRepository;
  6. public interface DocumentDao extends JpaRepository<Document,Long> {
  7. Page<Document> findAll(Specification<Document> specification,Pageable pageable);
  8. }
import org.carrot.domain.Document;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.repository.JpaRepository;

public interface DocumentDao extends JpaRepository<Document,Long> {
	Page<Document> findAll(Specification<Document> specification,Pageable pageable);
}
Util:
  1. import java.io.File;
  2. import java.io.FileOutputStream;
  3. public class FileUtil {
  4. public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {
  5. File targetFile = new File(filePath);
  6. if(!targetFile.exists()){
  7. targetFile.mkdirs(); //创建文件夹
  8. }
  9. FileOutputStream out = new FileOutputStream(filePath+fileName);
  10. out.write(file);
  11. out.flush();
  12. out.close();
  13. }
  14. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值