文件的上传:
1.配置xml
<bean id="multipartResolver" class="springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEconding" value="utf-8">
</bean>
2.页面
<form action="" method="post" enctype="multipart/form-data">
文件<input type="file"name="file">
<input type="submit" type="上传">
</form>
3.创建controller
public String upload(@RequestParam("file") CommonsMultipartFile file,httpSession session){
system.out.println(file.getName); 上传的名字
system.out.println(file.getOriginalFilename()); 上传的文件名字
system.out.println(file.getContextType()); 上传文件的类型
system.out.println(file.getSize()); 上传文件的大小
ServletContext applicstion=session.getServletContext();
String uploaddir =applicstion.getRealPath("/WEB-INF/upload");
file.transferTo(new File(uploaddir,file.getOriginaFilename()));
return "redirect: upload ";
}
文件的下载:
1.页面
<a href="${pageContext.request.contextPath}/download "></a>
2.创建controller
public String download(httpServletResponse response,httpSession session){
先读 inputStream in=null;
再写 outputStream out=null;
显示下载后的文件名字 Response.setHeader("content-disosition","attachment;filename=下载文件的名字".getbytes("utf-8"),"iso8859-1");
ServletContext applicstion=session.getServletContext();
文件所在路径 in=new FileInputStream(application.getRealPath("file/abc.text"));
out=new FileOutputStream();
byte[] b= new byte[2048];
int n;
while((n=in.read(b))!=-1){
out.writer(b,0,n);
}
if(in!=null){
in.close();
}
if(out!=null){
in.close();
}
SpringMVC文件上传与下载
最新推荐文章于 2022-05-02 14:14:26 发布
本文详细介绍了使用Spring框架实现文件上传和下载的具体步骤。包括配置文件解析、前端表单设置、后端控制器处理等关键环节,并展示了如何读取和保存文件、如何设置HTTP响应头以实现文件下载等功能。
6万+

被折叠的 条评论
为什么被折叠?



