spring roo 开发meavn项目(四)文件操作:上传,下载,本地复制,删除文件

pom文件中加入工具包引用

<span style="white-space:pre">		</span><dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>1.3.1</version>
		</dependency>
		
		<dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
			<version>2.4</version>
		</dependency>

文件操作工具类

package com.collegepatent.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.channels.FileChannel;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

/**
 * 文件上传下载操作类
 * 
 * @author xc
 *
 */
@Component(value = "fileoperate")
public class FileOperate {

	private static final String UPLOADDIR = "uploadDir/";

	/**
	 * 上传文件
	 * 
	 * @param uploadtype
	 *            上传文件的模块:专利,提案等
	 * @param fileid
	 *            附件所对应文档的ID
	 * @param uploadfiletype
	 *            上传的附件种类:技术交底书,其它文件等
	 * @author xc
	 */
	public static String upload(MultipartFile mfile, String uploadtype, String fileid, String uploadfiletype)
			throws Exception {

		String fileName = mfile.getOriginalFilename();
		if (!fileName.equals("")) {
			String uploadDir = "/collegepatent/" + uploadtype + "/" + fileid + "/" + uploadfiletype + "/";
			File file = new File(uploadDir);

			if (!file.exists()) {
				file.mkdirs();
			}

			String finalName = uploadDir + fileName;
			FileCopyUtils.copy(mfile.getInputStream(), new FileOutputStream(finalName));
			return fileName;
		} else
			return "NoFile";
	}

	/**
	 * 复制文件
	 * 
	 * @param srcFileName
	 *            待复制的文件名
	 * @param descFileName
	 *            目标文件名
	 * @param overlay
	 *            如果目标文件存在,是否覆盖
	 * @return 如果复制成功返回true,否则返回false
	 * @author xc
	 */
	public static boolean copyFile(String srcFileName, String destFileName, boolean overlay) {
		File srcFile = new File(srcFileName);

		// 判断源文件是否存在
		if (!srcFile.exists()) {
			return false;
		} else if (!srcFile.isFile()) {
			return false;
		}

		// 判断目标文件是否存在
		File destFile = new File(destFileName);
		if (destFile.exists()) {
			// 如果目标文件存在并允许覆盖
			if (overlay) {
				// 删除已经存在的目标文件,无论目标文件是目录还是单个文件
				new File(destFileName).delete();
			}
		} else {
			// 如果目标文件所在目录不存在,则创建目录
			if (!destFile.getParentFile().exists()) {
				// 目标文件所在目录不存在
				if (!destFile.getParentFile().mkdirs()) {
					// 复制文件失败:创建目标文件所在目录失败
					return false;
				}
			}
		}

		// 复制文件
		int byteread = 0; // 读取的字节数
		InputStream in = null;
		OutputStream out = null;

		try {
			in = new FileInputStream(srcFile);
			out = new FileOutputStream(destFile);
			byte[] buffer = new byte[1024];

			while ((byteread = in.read(buffer)) != -1) {
				out.write(buffer, 0, byteread);
			}
			return true;
		} catch (FileNotFoundException e) {
			return false;
		} catch (IOException e) {
			return false;
		} finally {
			try {
				if (out != null)
					out.close();
				if (in != null)
					in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	/** 
	 * 删除文件 
	 * @param   sPath    要删除的文件地址
	 * @author xc
	 */  
	public boolean deleteFile(String sPath) {  
	 
	   File file = new File(sPath);  
	    // 路径为文件且不为空则进行删除  
	    if (file.isFile() && file.exists()) {  
	        file.delete();  
	        return true;  
	    }  
	    return false;  
	}  
	  /**
     * 删除目录下的所有文件及子目录下所有文件
     */
   public boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            for (int i=0; i<children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        // 目录此时为空,可以删除
        return dir.delete();
    }
	/**
	 * 下载
	 * 
	 * @author xc
	 */
	public static void download( HttpServletResponse response, 	String downLoadPath
			 ) throws Exception {
		response.setContentType("text/html;charset=UTF-8");
	
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		String contentType="application/octet-stream";
		
		long fileLength = new File(downLoadPath).length();
		String realName=new File(downLoadPath).getName();
		response.setContentType(contentType);
		response.setHeader("Content-disposition",
				"attachment; filename=" + new String(realName.getBytes("utf-8"), "ISO8859-1"));
		response.setHeader("Content-Length", String.valueOf(fileLength));

		bis = new BufferedInputStream(new FileInputStream(downLoadPath));
		bos = new BufferedOutputStream(response.getOutputStream());
		byte[] buff = new byte[2048];
		int bytesRead;
		while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
			bos.write(buff, 0, bytesRead);
		}
		bis.close();
		bos.close();
	}
}

文件上传,复制,删除的使用

package com.collegepatent.web;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.roo.addon.web.mvc.controller.scaffold.RooWebScaffold;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.collegepatent.security.GetUserName;
import com.collegepatent.util.FileOperate;


@RequestMapping("/file")
@Controller

public class FileController {
	
	@Resource
	FileOperate fileoperate;
	
	
    @RequestMapping(value = "list")  
    public Object toUpload(ModelMap map) {  
    	return "file"; 
    }  
  
    /** 
     * 上传文件 
     *  
     * @author xc 
     */  
   
    @RequestMapping(method = RequestMethod.POST, value = "upload", produces = "application/json")
	@ResponseBody
    public Object upload(HttpServletRequest request,String uploadtype,String fileid,String filename) throws Exception {  
  
     
      List<MultipartFile> files = ((MultipartHttpServletRequest)request).getFiles(filename);
   /*   String uploadtype=request.getParameter("uploadtype");
      String fileid=request.getParameter("fileid");
      String uploadfiletype=request.getParameter("uploadfiletype");
      */
      if(files.size()!=0)
      {
    	  filename= fileoperate.upload(files.get(0), uploadtype, fileid, filename+"path");
      }
      else
    	  filename="none";
  	Map<String, Object> map = new HashMap<String, Object>();
	map.put("filename", filename);
	return map;
      //  return technicaldocpath;  
    }  
    /** 
     * 复制和删除文件 
     *  
     * @author xc 
     */  
   
    @RequestMapping(method = RequestMethod.GET, value = "copy", produces = "application/json")
	@ResponseBody
    public Object copy()  {  
  
    	String srcFileName="/test123.docx";
    	String destFileName="/ok/test123.docx"; 
	    boolean overlay=true;
	   
	    fileoperate.copyFile(srcFileName, destFileName, overlay);
	    fileoperate.deleteFile(srcFileName);
	    return true;

    }  
 
}

文件下载的使用

	/**
	 * description: 文件下载
	 * 
	 * @author xc
	 */
	@RequestMapping(method = RequestMethod.GET, value = "downloadProposalFile", produces = "application/json")
	@ResponseBody
	public Object downloadProposalFile( HttpServletResponse response,String proposalid,String filetype){
		Proposal pr=Proposal.findProposal(Long.parseLong(proposalid));
		String downloadpath="";
		if(filetype.equals("technicaldocpath")) 
		{
			downloadpath=pr.getTechnicaldocpath();
		}
		if(filetype.equals("otherfilepath")) 
		{
			downloadpath=pr.getOtherfilepath();
		}
		if(downloadpath.equals(""))
			return false;
		else
		{
			try
			{
				fileoperate.download(response, downloadpath);
				return true;
			}catch(Exception e)
			{
				return false;
			}
			
		}
	}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值