基于ssm框架,在网页上实现文档的上传和下载功能。
在pom.xml中注入上传文件所需的依赖和添加了相应的配置文件情况下。
文件上传
FileController.java
/**
* 上传单个文件操作
* @param RequestParam 括号中的参数名file和表单的input节点的name属性值一致
* @return
*/
@RequestMapping(value="/doUpload", method=RequestMethod.POST)
public String doUploadFile(@RequestParam("file") MultipartFile file){
if(!file.isEmpty()){
try {
//这里将上传得到的文件保存至 d:\\temp\\file 目录
FileUtils.copyInputStreamToFile(file.getInputStream(), new File("d:\\temp\\file\\",
System.currentTimeMillis()+ file.getOriginalFilename()));
} catch (IOException e) {
e.printStackTrace();
}
}
return "success"; //上传成功则跳转至此success.jsp页面
}
//定位到上传单个文件界面 /hello/upload
@RequestMapping(value="/upload", method=RequestMethod.GET)
public String showUploadPage(){
return "uploadFile"; //view文件夹下的上传单个文件的页面
}
success.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<link rel="stylesheet" href="<%=request.getContextPath()%>/resources/css/main.css" type="text/css" />`在这里插入代码片`
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>上传文件成功页面</title>
</head>
<body>
<div align="center">
<h1>Success</h1>
</div>
</body>
</html>
File.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>上传单个文件示例</title>
<link rel="stylesheet" href="<%=request.getContextPath()%>/resources/css/main.css" type="text/css" />
</head>
<body>
<div align="center">
<h1>上传附件</h1>
<form method="post" action="/HelloSpringMVC/hello/doUpload" enctype="multipart/form-data">
<input type="file" name="file"/>
<button type="submit" >提交</button>
</form>
</div>
</body>
</html>
注:
(1)form表单提交的类型一定要加上enctype=“multipart/form-data”,表示不对所提交的内容编码。
(2)action=“” 路径中前面要加项目名,这里项目名是HelloSpringMVC。
(3)doUpload是本表单所提交的对应的处理方法。名为doUpload。
(4)input节点的name="file"中的file与doUpload方法所接收的参数名称一致。
文件下载
FileController.java
/**
根据文档的id在数据库中查找对应的文件名 文件名称=fileService.findUrl(id)
项目的同级目录的productImgs下 request.getSession().getServletContext().getRealPath("/") + ".." + File.separator
**/
@RequestMapping("/download/{id}")
public String download(HttpServletRequest request, HttpServletResponse response, @PathVariable("id") Integer id){
//1.获取要下载的文件的绝对路径
String realPath = request.getSession().getServletContext().getRealPath("/") + ".." + File.separator + "productImgs"+
File.separator+fileService.findUrl(id);
System.out.println(realPath);
//2.获取要下载的文件名
String fileName = realPath.substring(realPath.lastIndexOf("\\")+1);
// String fileName=fileService.findUrl(id);这个也行
// System.out.println(fileName);
response.setContentType("text/html;charset=utf-8");
try {
request.setCharacterEncoding("UTF-8");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
java.io.BufferedInputStream bis = null;
java.io.BufferedOutputStream bos = null;
String downLoadPath = realPath; //注意不同系统的分隔符
try {
long fileLength = new File(downLoadPath).length();
response.setContentType("application/x-msdownload;");
response.setHeader("Content-disposition", "attachment; filename=" + new String(fileName.getBytes("utf-8"), "ISO8859-1"));
response.setHeader("Content-Length", String.valueOf(fileLength));
bis = new BufferedInputStream(new FileInputStream(downLoadPath));
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);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null)
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
if (bos != null)
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
FileService.java
public interface FileService {
// /**查询路径*/
String findUrl(Integer id);
}
FileServiceImpl.java
@Service
@Transactional(propagation= Propagation.REQUIRED)
public class FileServiceImpl implements FileService {
@Autowired
private FileDOMapper fileDOMapper;
@Override
public String findUrl(Integer id) {
return fileDOMapper.findUrl(id);
}
}
FileDOMapper.java
public interface FileDOMapper {
String findUrl(@Param("id") Integer id);
}
FileDOMapper.xml
select file_url from sys_file where id = #{id}前端的代码
File.jsp
<a href="javascript:void(0)" onclick="downloadFun();">下载</a>
File.js
function downloadFun() {
var row = dg.datagrid('getSelected');
//根据id选择下载的文件
if (rowIsNull(row)) return;
window.location.href=rootPath + '/file/file/download/'+row.id;
//跳转到controller的下载方法中
}
选择第一项下载
下载完成图
至此,一个完整的文件上传和下载就成功了。
在完成工作时要会搜索网上的文档,并把网上的资料和实际的项目相整合才能提高工作的效率。
参考:https://blog.csdn.net/u012660464/article/details/53434331
https://blog.csdn.net/geloin/article/details/7537425?utm_medium=distribute.pc_relevant_t0.none-task-blog-BlogCommendFromMachineLearnPai2-1.channel_param&depth_1-utm_source=distribute.pc_relevant_t0.none-task-blog-BlogCommendFromMachineLearnPai2-1.channel_param