上传步骤:
- 1.在applicationContext.xml中添加配置
<!-- 配置多媒体文件解析器 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 设定默认编码 -->
<property name="defaultEncoding" value="UTF-8"></property>
<!-- 设定文件上传的最大值2MB, 2*1024*1024 -->
<property name="maxUploadSize" value="2097152"></property>
<!--resolveLazily属性启用是为了推迟文件解析,以便在UploadAction 中捕获文件大小异常-->
<property name="resolveLazily" value="true"/>
</bean>
<form action="/StudentInfo/StudentHandler/sc/${sessionScope.sid }" enctype="multipart/form-data" method="post">
<input type="file" name="file" width="120px">
<button type="submit">上传</button>
</form>
// 上传Excel
@RequestMapping(value = "/sc/{sid}", method = RequestMethod.POST)
public String sc(@PathVariable("sid") String sid, @RequestParam("file") MultipartFile file, HttpServletRequest request,
Model model) throws IOException {
// uploads文件夹位置
String rootPath = request.getSession().getServletContext().getRealPath("WEB-INF/upload");
// 原始名称
String originalFileName = file.getOriginalFilename();
// 新文件名
String newFileName = "sliver"+ originalFileName;
// 新文件
File newFile = new File(rootPath + newFileName);
// 判断目标文件所在目录是否存在
if( !newFile.getParentFile().exists()) {
// 如果目标文件所在的目录不存在,则创建父目录
newFile.getParentFile().mkdirs();
}
System.out.println(newFile);
// 将内存中的数据写入磁盘
try {
file.transferTo(newFile);
} catch (IOException e) {
return "fail";
} catch (IllegalStateException e) {
return "fail";
}
Guoc guoc = new Guoc();
guoc.setUrl(newFileName);
guoc.setSid(sid);
studentService.insertguoc(guoc);
return "success";
}
下载Excel步骤
@RequestMapping(value = "/xz", method = RequestMethod.GET)
public void down(String gid,HttpServletRequest request, HttpServletResponse response) throws Exception{
//根据id查询存在数据库的文件名称
Guoc guoc = studentService.selectguocid(gid);
String url = guoc.getUrl(); //文件名称
System.out.println(url);
//获取资源目录下的文件 这个url就是文件名 就可以找到文件夹下面的这个文件
String fileName = request.getSession().getServletContext().getRealPath("WEB-INF/upload")+url;
//获取输入流
InputStream bis = new BufferedInputStream(new FileInputStream(new File(fileName)));
//假如以中文名下载的话
String filename = url;
//转码,免得文件名中文乱码
filename = URLEncoder.encode(filename,"UTF-8");
//设置文件下载头
response.addHeader("Content-Disposition", "attachment;filename=" + filename);
//1.设置文件ContentType类型,这样设置,会自动判断下载文件类型
response.setContentType("multipart/form-data");
BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
int len = 0;
while((len = bis.read()) != -1){
out.write(len);
out.flush();
}
out.close();
}
````
网友评论