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

文档管理需求如题。

Entity:

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:

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:

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:
import java.io.File;
import java.io.FileOutputStream;

public class FileUtil {
	
    public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception { 
        File targetFile = new File(filePath);  
        if(!targetFile.exists()){    
            targetFile.mkdirs();   //创建文件夹 
        }       
        FileOutputStream out = new FileOutputStream(filePath+fileName);
        out.write(file);
        out.flush();
        out.close();
    }

}




    

猜你喜欢

转载自blog.csdn.net/ArvinXiong/article/details/80761245