1. 文件上传
(1)前端代码
<form id="uploadForm" role="form" action="" method="post" enctype="multipart/form-data">
<div class="form-group">
<input type="file" id="inputFile" name="selectFile" multiple="multiple" class="form-control"/>
</div>
</form>
注意:enctype="multipart/form-data" 是用来设置表单的MIME编码。默认情况,这个编码格式是
application/x-www-form-urlencoded,不能用于文件上传。只有使用了multipart/form-data,才能完整的传递文件数据。multiple="multiple" 是用来设置选择多个文件,批量文件上传时使用。
(2)提交方式
可以使用ajax提交form表单:$("#uploadForm").submit();
如果需要传递带参数的url可以先给action赋值:$("#uploadForm").attr('action',‘url?id=’+id); 然后再提交表单。
(3)后台代码
public void uploadFile(HttpServletRequest request, HttpServletResponse response) throws Exception {
MultipartHttpServletRequest mulRequest = (MultipartHttpServletRequest) request;
MultipartFile mFile = mulRequest.getFile("selectFile"); // 得到上传文件
// 获得项目部署路径(默认在Tomact的webapps目录下)
String path = request.getSession().getServletContext().getRealPath("");
String fileName = mFile.getOriginalFilename(); // 得到上传文件的文件名
InputStream inputStream = mFile.getInputStream();
byte[] buff = new byte[1048576]; // 设置文件大小
int length = inputStream.read(buff);
//将文件上传到aa文件夹下
//path = path + "aa/" + fileName; // Linux环境
path = path + "aa\\" + fileName; // Windows环境
FileOutputStream outputStream = new FileOutputStream(path); // 文件流写到服务器
outputStream.write(buff, 0, length);
inputStream.close();
outputStream.close();
}
2. 文件下载
public void downloadFile(HttpServletRequest request, HttpServletResponse response) throws Exception {
response.setContentType("text/html;charset=UTF-8");
request.setCharacterEncoding("UTF-8");
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
String fileName = request.getParameter("fileName"); // 下载文件名
String ctxPath = request.getSession().getServletContext().getRealPath("");// 获得项目部署路径
ctxPath = ctxPath + "aa\\" + fileName; // Windows环境
//ctxPath = ctxPath + "aa/" + fileName;// Linux环境
long fileLength = new File(ctxPath).length();
response.setContentType("application/octet-stream");
response.setHeader("Content-disposition", "attachment; filename=" + new String(fileName.getBytes("UTF-8"), "iso-8859-1")); // 解决中文名称乱码问题
response.setHeader("Content-Length", String.valueOf(fileLength));
bis = new BufferedInputStream(new FileInputStream(ctxPath));
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();
}