springmvc+ftp文件上传下载+MultipartFile

一、首先在form中加上enctype="multipart/form-data"

<form id="add" class="form-horizontal" enctype="multipart/form-data">

二、然后xml文件配置添加
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<!-- 指定所上传文件的总大小不能超过20000KB..... -->
		<property name="maxUploadSize" value="20000000" />
</bean>

三、后台控制层,保存多个文件

@RequestMapping("/save")
	@ResponseBody
	public String save(@RequestParam("owners") String[] owners,
			@ModelAttribute("messageSend") MessageSend messageSend,@RequestParam("uploadFile") MultipartFile[] uploadFile) {
		StringBuffer sb = new StringBuffer();
		String basePath="/message";//设置服务器中文件保存的根目录
		Date now = new Date(); 
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
		String filePath = dateFormat.format(now); //根据当前时间设置文件保存的子目录
		if(uploadFile != null && uploadFile.length > 0){
				if(!ftp.uploadFile(uploadFile, basePath, filePath)){
					return "error";
				}
				for(int i=0; i<uploadFile.length; i++){
					String fileName;
						fileName = new String(uploadFile[i].getOriginalFilename());  
						if(i!=0){
							sb.append(",");
						}
						sb.append(fileName);//用逗号连接文件名存入数据库
				}
				
		}
		/**...*/存入数据库处理
		return "error";
	}


四、ftp处理

@Component
public class FTPUtil {
	
	@Autowired
	private FTPClientPool fTPClientPool;
	
	public boolean uploadFile(MultipartFile[] uploadFile, String basePath, String filePath){
		try {
			FTPClient client = fTPClientPool.borrowObject();

			//切换到上传目录  ,basepath需已存在
            if (!client.changeWorkingDirectory(basePath+filePath)) {  
                //如果目录不存在创建目录  
                String[] dirs = filePath.split("/");  
                String tempPath = basePath;  
                for (String dir : dirs) {  
                    if (null == dir || "".equals(dir)) continue;  
                    tempPath += "/" + dir;  
                    if (!client.changeWorkingDirectory(tempPath)) {  
                        if (!client.makeDirectory(tempPath)) {  
                            return false;  
                        } else {  
                        	client.changeWorkingDirectory(tempPath);  
                        }  
                    }  
                }  
            }   
			
			if(uploadFile != null && uploadFile.length > 0){
				for(int i=0;i<uploadFile.length;i++){
					MultipartFile file = uploadFile[i];
					saveFile(file,client);
				}
			}
			fTPClientPool.returnObject(client);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		return true;
	}
	
	private boolean saveFile(MultipartFile file,FTPClient client){
		boolean success = false;
		InputStream inStream = null;
		try {
			String fileName = new String(file.getOriginalFilename());
			inStream = file.getInputStream();
			success = client.storeFile(fileName, inStream);
			if (success == true) {
                return success;
            }
		}  catch (Exception e) {
		}finally {
            if (inStream != null) {
                try {
                    inStream.close();
                } catch (IOException e) {
                }
            }
        }
		return success;
	}
	
	public boolean downloadFile(HttpServletResponse response, String fileName, String path){
		response.setCharacterEncoding("UTF-8");
		response.setContentType("multipart/form-data;charset=UTF-8");
		try {
			FTPClient client = fTPClientPool.borrowObject();
			client.changeWorkingDirectory(path);
			FTPFile[] fs = client.listFiles();
			for(FTPFile ff: fs){
				if(ff.getName().equals(fileName)){
					response.setHeader("Content-Disposition", "attachment;fileName="+ new String( ff.getName().getBytes("gb2312"), "ISO8859-1" ) );
					OutputStream os = response.getOutputStream();
					client.retrieveFile(ff.getName(), os);
					os.flush();
					os.close();
					break;
				}
			}
			fTPClientPool.returnObject(client);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return true;
	}
}



  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值