JavaEE进阶 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 + "]";
}
}
后台代码就这么简单,接下来看看前台的代码:
对应文件信息加一个这个。就可以实现了!下载//下载文件
function downLoad(file_id) {
window.location.href = 'downLoadFile.action?id='+file_id;
}
测试:
文件:
这样就实现文件下载的功能了!
总结:
SpringMVC做文件下载很简单。其实,用普通的jsp+servlet也是可以用这个方法来这样做,只是我写的demo里用了SpringMVC,所以就叫SpringMVC咯!
以上,关于Java的全部内容讲解完毕啦,欢迎大家继续关注!更多关于Java的干货请关注职坐标Java频道!希望这篇Java编程文章可以帮助到你。总之,同学们,你想要的职坐标Java频道都能找到!
本文由职坐标整理并发布,希望对同学们学习Java的知识有所帮助。了解更多详情请关注职坐标Java频道!