框架是基于spring+myBatis的。
前台页面的部分代码:
上传文件:
*上传文件格式为xls,xlsx,txt,csv文件!
{
title : '操作',
halign : 'center',
align : 'center',
width : 80,
field : 'FILE_PATH',
formatter: function(value,row,index){
var path = "${ctx}/file/download.do?filePath=" + value ;
var button = '';
return "" + button + "";
}
上传功能的方法:
@RequestMapping("/upLoadFile")
public String upload(@RequestParam(value = "file", required = false) MultipartFile file, ModelMap model, HttpServletRequest request)
throws Exception {
//设置相对路径
String realPath = request.getSession().getServl服务器托管网etContext().getRealPath("/upload");
//获取文件的格式
String extention = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1);
//对格式进行筛选
if(extention.equalsIgnoreCase("xls") || extention.equalsIgnoreCase("xlsx") || extention.equalsIgnoreCase("txt")
|| extention.equalsIgnoreCase("csv")) {
//在路径下创建文件夹
File f = new File(realPath);
String fileName = file.getOriginalFilename();
String uploadPath = realPath + File.separator + fileName;
if(!f.exists()) {
f.mkdir();
}
//文件的传输
file.transferTo(new File(uploadPath));
Upload upload = new Upload();
upload.setFileName(fileName);
upload.setFileLength(String.valueOf(file.getSize()));
upload.setFileOwner(super.getLoginUser(request).getLoginId());
upload.setFilePath("/upload/" + fileName);
//将文件的基本信息存到数据库
fileQueryService.saveFile(upload);
request.setAttribute("info","文件上传成功!");
} else {
request.setAttribute("info","文件类型不正确,请上传格式为xls,xlsx,txt,csv文件!");
}
return "page/file/fileInteraction";
}
下载功能的方法:
@RequestMapping("/download")
public String download(String filePath, HttpServletRequest request,
HttpServletResponse response) {
try {
//获取文件名
String fileName = filePath.substring(filePath.lastIndexOf("/")+1);
System.out.println(服务器托管网filePath);
response.setCharacterEncoding("utf-8");
response.setContentType("multipart/form-data");
//处理下载弹出框名字的编码问题
response.setHeader("Content-Disposition", "attachment;fileName="
+ new String( fileName.getBytes("gb2312"), "ISO8859-1" ));
//获取文件的下载路径
String path = request.getSession().getServletContext().getRealPath(filePath);
System.out.println(path);
//利用输入输出流对文件进行下载
InputStream inputStream = new FileInputStream(new File(path));
OutputStream os = response.getOutputStream();
byte[] b = new byte[2048];
int length;
while ((length = inputStream.read(b)) > 0) {
os.write(b, 0, length);
}
// 这里主要关闭。
os.close();
inputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// 返回值要注意,要不然就出现下面这句错误!
//java+getOutputStream() has already been called for this response
return null;
}
参考文章:http://blog.ncmem.com/wordpress/2023/11/26/javaweb项目中的文件上传下载功能的实现/
服务器托管,北京服务器托管,服务器租用 http://www.fwqtg.net
机房租用,北京机房租用,IDC机房托管, http://www.fwqtg.net
1 OS_object OS_object由下面宏OS_OBJECT_DEC_BASE扩展而来: // 1. os/object.h OS_OBJECT_DECL_BASE(object, NSObject); // 2. os/object.h #defin…