一、springmvc实现文件上传的步骤
1、实现上传单张图片
1、导入pom 坐标
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
2、编写上传页面
注意:页面上通过 input 来准备 file 组件,该标签必须给定 name 属性值(该 name 不能和实体类的属性名一致),要求 form 表单必须给定一个属性:enctype=“multipart/form-data”,同时请求必须为post:method=“post”
<h2>文件上传</h2>
<form action="up" method="post" enctype="multipart/form-data" >
用户名:<input type="text" name="name" value="jim" /><br/>
头像:<input type="file" name="myfile" /><br/>
<input type="submit" value="上传" />
</form>
3、文件上传配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation=" http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.kuang.controller"/>
<mvc:default-servlet-handler/>
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<constructor-arg value="UTF-8"/>
</bean>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper">
<bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
<property name="failOnEmptyBeans" value="false"/>
</bean>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8"/>
<property name="maxUploadSize" value="10485760"/>
<property name="maxInMemorySize" value="40960"/>
</bean>
</beans>
4、编写Controller类
@RequestMapping("/up")
public String testUP(@RequestParam CommonsMultipartFile myfile, String name, Model m, HttpSession session) throws Exception{
String realpath = session.getServletContext().getRealPath("\\upload");
System.out.println("上传文件保存地址:"+realpath);
String fname = myfile.getOriginalFilename();
String ftype = fname.substring(fname.lastIndexOf("."));
String filename = UUID.randomUUID().toString();
String fullname = realpath+"\\"+filename+ftype;
System.out.println("上传的文件名:"+fname);
byte[] b = myfile.getBytes();
System.out.println(fullname);
FileOutputStream out = new FileOutputStream(fullname);
out.write(b);
out.flush();
out.close();
m.addAttribute("fname", fname);
return "ok";
}
5、上传成功后跳转的页面
<%@ 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>Insert title here</title>
</head>
<body>
<%
String fname = (String)request.getAttribute("fname");
%>
<h3>成功上传了一个文件 <%= fname %></h3>
</body>
</html>
效果图:
2、实现上传多张图片
1、编写上传页面
<h2>文件上传多张图片</h2>
<form action="up2" method="post" enctype="multipart/form-data" >
用户名:<input type="text" name="name" value="jim" /><br/>
文件1:<input type="file" name="myfile" /><br/>
文件2:<input type="file" name="myfile" /><br/>
<input type="submit" value="上传" />
</form>
2、编写Controller类
@RequestMapping("/up2")
public String testUP2(@RequestParam CommonsMultipartFile[] myfile, String name, Model m, HttpSession session) throws Exception{
ArrayList listname =new ArrayList();
ArrayList listname2 =new ArrayList();
String realpath = session.getServletContext().getRealPath(File.separator+"upload");
System.out.println("上传文件保存地址:"+realpath);
for(CommonsMultipartFile cf :myfile){
String fname = cf.getOriginalFilename();
String ftype = fname.substring(fname.lastIndexOf("."));
String filename = UUID.randomUUID().toString();
String fullname = realpath+File.separator+filename+ftype;
System.out.println(fname);
System.out.println(fullname);
cf.transferTo(new File(fullname));
listname.add(fname);
listname2.add(filename+ftype);
m.addAttribute("flist", listname);
m.addAttribute("flist2", listname2);
}
return "ok2";
}
3、上传成功后跳转的页面
<%@ page contentType="text/html;charset=UTF-8" import="java.util.*" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%
ArrayList flist = (ArrayList)request.getAttribute("flist");
ArrayList flist2 = (ArrayList)request.getAttribute("flist2");
%>
<h3>成功上传了
<%
for(int i = 0 ; i < flist.size() ;i++){
String n = (String)flist.get(i);
%>
<%=n %>,
<%
}
%>文件 </h3>
<hr/>
<%
for(int i = 0 ; i < flist2.size() ;i++){
String name = (String)flist2.get(i);
%>
<img alt="图片加载失败" title="上传的图片" src="<%=request.getContextPath()%>/upload/<%=name%>" />
<%
}
%>
</body>
</html>
二、springmvc实现文件下载的步骤
1、显示所有下载图片
这里我们先显示文件夹中所有的图片,然后在点击单个图片进行下载。
<h2><a href="xzview" >下载页面</a></h2>
2、编写Controller 类
@RequestMapping("/xzview")
public String testXzView(Model m, HttpSession session){
String realpath = session.getServletContext().getRealPath(File.separator+"upload");
File f = new File(realpath);
String[] fs = f.list();
m.addAttribute("fs", fs);
return "view";
}
@RequestMapping("/xzimgcon")
public void xzimgcon(String fname , HttpServletRequest request, HttpServletResponse response){
response.setContentType("image/jpeg;charset=utf-8");
HttpSession session = request.getSession();
ServletContext sc = session.getServletContext();
String realpath = sc.getRealPath("upload\\");
response.setHeader("Content-disposition", "attachment;filename=" + fname);
try {
FileInputStream fin = new FileInputStream(realpath + "\\" + fname);
ServletOutputStream fout = response.getOutputStream();
byte[] b = new byte[fin.available()];
fin.read(b);fout.write(b);fin.close();fout.flush();fout.close();
} catch (Exception e) {
System.out.println("下载文件出现异常");
e.printStackTrace();
}
}
3、实现下载页面
<%@ 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>Insert title here</title>
</head>
<body>
<h1>下载页面</h1>
<%
String[] fs = (String[])request.getAttribute("fs");
%>
<%
for(int i = 0 ; i < fs.length; i++){
String fname = fs[i];
%>
<img width="100" height="100" src="<%=request.getContextPath()+"/upload/"+fname %>" /><a href="xzimgcon?fname=<%=fname%>">下载</a>
<%
}
%>
</body>
</html>
效果图:
如果有收获!!! 希望老铁们来个三连,点赞、收藏、转发。
创作不易,别忘点个赞,可以让更多的人看到这篇文章,顺便鼓励我写出更好的博客
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)