随笔(一) - - springmvc实现文件下载

前言:

        实现文件下载的功能网上有很多案例。在这小编随笔写一篇关于springmvc实现文件下载的随笔!如果有兴趣的同学可以看一下,没有太多的技术要点。


实现步骤:        

        先说说开发的思路,有思路了开发也就简单了。没思路开发就很难了!

        一:我们说是下载文件吧,直接一个给前台一个url不就好了!这种方法确实可以,但是如果浏览器能解析的文件的话就会直接在浏览器打开了。比如:你想下载一个txt的文本,可是浏览器可以解析就给你直接打开了。这不符合吧!所以第一步我们要先确定文件是否是都下载,还是允许浏览器解析。

        二:确定了之后,我们在前台放一个链接!后台用流的方式回写回去。(注意:尽量用缓存流来实现,这样高效一些,如果字节流且设置的读取不大,下载大文件时,呵呵!)

       

代码:

        这里是filUtils类,主要放关于文件的东西。

package com.wen.util;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;

public class FileUtil {
	
	/**
	 * 读取到字节数组2
	 * 
	 * @param filePath
	 * @return
	 * @throws IOException
	 */
	public static byte[] toByteArray2(String filePath) throws IOException {

		File f = new File(filePath);
		if (!f.exists()) {
			throw new FileNotFoundException(filePath);
		}

		FileChannel channel = null;
		FileInputStream fs = null;
		try {
			fs = new FileInputStream(f);
			channel = fs.getChannel();
			ByteBuffer byteBuffer = ByteBuffer.allocate((int) channel.size());
			while ((channel.read(byteBuffer)) > 0) {
				// do nothing
				// System.out.println("reading");
			}
			return byteBuffer.array();
		} catch (IOException e) {
			e.printStackTrace();
			throw e;
		} finally {
			try {
				channel.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				fs.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	
         这个是文件下载类(设置下载的方式等):

    

package com.wen.util;

import java.io.BufferedOutputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletResponse;


/**
 * 下载文件
 * @version
 */
public class FileDownload {

	/**
	 * @param response 
	 * @param filePath		//文件完整路径(包括文件名和扩展名)
	 * @param fileName		//下载后看到的文件名
	 * @return  文件名
	 */
	public static void fileDownload(final HttpServletResponse response, String filePath, String fileName) throws Exception{  
		     
		    byte[] data = FileUtil.toByteArray2(filePath);  
		    fileName = URLEncoder.encode(fileName, "UTF-8");  
		    response.reset();  
		    //保证文件都是下载的,不是解析
		    response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");  
		    response.addHeader("Content-Length", "" + data.length);  
		    response.setContentType("application/octet-stream;charset=UTF-8");
		    //缓冲流
		    OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());  
		    outputStream.write(data);  
		    //刷新缓存,不懂就理解为2胖子一起出门给堵住了,你一脚踹过去让他们出去
		    outputStream.flush();  
		    //保持好习惯,用完就关掉
		    outputStream.close();
		    response.flushBuffer();
		    
		} 

}
            接下来就是我们springmvc的文件下载类了!
package com.wen.controller.admin;

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

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.websocket.server.PathParam;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.wen.bean.ExtendFreaction;
import com.wen.bean.FileInformation;
import com.wen.bean.Freaction;
import com.wen.service.user.AdminServices;
import com.wen.service.user.UserServices;
import com.wen.shiro.manager.ShiroManager;
import com.wen.util.Constant;
import com.wen.util.FileDownload;
import com.wen.util.ObjectExcelView;

@Controller
public class AdminController {
	@Resource
	AdminServices adminService;
	@Resource
	UserServices userServices;



	/**
	 * 用户下载文件
	 * @return
	 */
	@RequestMapping(value = "downLoadFile")
	public void downLoadFile(HttpServletResponse response, Integer  id) {	
		//从数据库查文件的信息
		FileInformation fileInformation=adminService.getFileInformation(id);
		
		try {//开始下载了呗
			FileDownload.fileDownload(response, fileInformation.getPath(), fileInformation.getFilename());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	
}
        附:FileInformation类
package com.wen.bean;

import java.util.Date;

import com.fasterxml.jackson.annotation.JsonFormat;



public class FileInformation {
	private int id;
	private String filename;
	private String path;
	private String filetype;
	
	private Date time;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getFilename() {
		return filename;
	}

	public void setFilename(String filename) {
		this.filename = filename;
	}

	public String getPath() {
		return path;
	}

	public void setPath(String path) {
		this.path = path;
	}

	public String getFiletype() {
		return filetype;
	}

	public void setFiletype(String filetype) {
		this.filetype = filetype;
	}
	
	public Date getTime() {
		return time;
	}

	public void setTime(Date time) {
		this.time = time;
	}

	@Override
	public String toString() {
		return "FileInformation [id=" + id + ", filename=" + filename + ", path=" + path + ", filetype=" + filetype
				+ ", time=" + time + "]";
	}

}

        后台代码就这么简单,接下来看看前台的代码:

            对应文件信息加一个这个。就可以实现了!

    <a href="javascript:void;"  title="下载" οnclick="downLoad('${fileInfo.id}');">下载</a>
		//下载文件
		function downLoad(file_id) {
			
			window.location.href = 'downLoadFile.action?id='+file_id;
		}
        测试:


        文件:

    

        这样就实现文件下载的功能了!


总结:

        springmvc做文件下载很简单。其实,用普通的jsp+servlet也是可以用这个方法来这样做,只是我写的demo里用了springmvc,所以就叫springmvc咯!下一次,小编会写ecxel的操作,并共享一些util工具类,方便大家编写代码,不需要重复造轮子!


        程序人生,与君共勉


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值