您的位置:首页 > 编程语言 > Java开发

基于SpringMVC的文件上传和下载

2017-04-06 23:03 706 查看
一  文件上传和下载需要的jar包



二 文件的上传:

     jsp页面:<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.get
4000
ContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>陈二狗的妖孽人生</title>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-1.9.1.js"></script>
</head>
<body>
<h1>SpringMVCDemo:${message}</h1>
<!-- <script type="text/javascript">
$(document).ready(function() {
alert("陈二狗的妖孽人生");
});
</script> -->
<form action="${pageContext.request.contextPath}/HelloWorld/uploadFile" method="POST" enctype="multipart/form-data">
<h2>文件上传</h2>
文件:<input type="file" name="uploadFile"/><br><br>
<input type="submit" value="上传">
<a href="${pageContext.request.contextPath }/HelloWorld/fileDownLoad?123.jpg">下载</a>
</form>
</body>
</html>
 Controller里面的文件上传的方法:
/**
* 文件上传
* @param uploadFile
* @param session
* @return
* @throws IOException
* @throws IllegalStateException
*/
@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
public String uploadFile(MultipartFile uploadFile, HttpSession session) throws Exception{
// 获取文件名称作为保存在服务器的文件的名称
String filename = uploadFile.getOriginalFilename();
// 前半部分路径, 目录,将WebRoot下一个名称为images文件夹 转换成绝对路径
String leftPath = session.getServletContext().getRealPath("/images");
// 进行路径拼接 = 前半部分路径 + 文件名称
File file = new File(leftPath, filename);
// 如果上传文件目录不存在 自动创建该文件夹
if (!file.exists()){
file.mkdirs();
}
uploadFile.transferTo(file);
return "loadFileSuccess";
} spingMVC配置文件配置如下:
<!-- 配置文件上传 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="50000000"></property>
<!-- <property name="maxUploadSizePerFile" value="5000000"></property> -->
<property name="defaultEncoding" value="utf-8"></property>
</bean>
三 文件的下载
  Controller里面的方法:

/**
* 文件下载
* @return
* @throws Exception
*/
@RequestMapping(value = "/fileDownLoad", method = RequestMethod.GET)
public ResponseEntity<byte[]> fileDownLoad()throws Exception{
File file = new File("E:\\相册\\微博\\123.jpg");
HttpHeaders headers = new HttpHeaders();
String fileName = new String("123.jpg".getBytes("utf-8"), "iso-8859-1"); // 解决中文乱码问题
headers.setContentDispositionFormData("attachment", fileName);
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: