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

java后台开发SpringMVC例子--图片上传下载

2018-01-24 15:04 507 查看
环境:

win7;jdk1.8_121;tomact8.0;Mysql;spring-4.3.0。需要安装及配置好jdk,mysql。

完整代码下载(需要的jar包已放在lib下)

http://download.csdn.net/download/yhhyhhyhhyhh/9913431


1.配置

连接数据库需要:
mysql-connector-java-5.0.8-bin.jar

服务器上运行servlet需要:
servlet-api.jar

文件上传需要:
com.springsource.org.apache.commons.fileupload-1.2.0.jar

com.springsource.org.apache.commons.io-1.4.0.jar

web.xml配置:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>TestOA</display-name>
<welcome-file-list>
<welcome-file>/WEB-INF/views/index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>oa</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- load-on-startup:表示启动容器时初始化该Servlet; -->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>oa</servlet-name>
<!-- url-pattern:表示哪些请求交给Spring Web MVC处理, “/” 是用来定义默认servlet映射的。 -->
<!-- 也可以如“*.html”表示拦截所有以html为扩展名的请求。 -->
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- 编码过滤器 -->
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter </filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/</url-pattern>
</filter-mapping>
</web-app>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
[/code]
servlet配置(这里为:oa-servlet.xml)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"> <!-- spring扫描注解的包 -->
<context:component-scan base-package="com.springmvc.test" />
<!-- 在Spring配置文件中配置ViewResolver -->
<!-- InternalResourceViewResolver:用于支持Servlet、JSP视图解析;
prefix和suffix:查找视图页面的前缀和后缀(前缀[逻辑视图名]后缀),
比如传进来的逻辑视图名为hello,则该该jsp视图页面应该存放在“WEB-INF/views/hello.jsp”;    -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<!--文件上传解析器配置 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 上传文件的总大小和单个文件的大小 -->
<property name="maxUploadSize" value="12345678900"/>
<property name="maxInMemorySize" value="10240100"/>
<property name="defaultEncoding" value="UTF-8"/>
</bean>
</beans>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
[/code]
数据库信息:



核心代码部分。
package com.springmvc.test;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

/*
* @Controller表示类注解
* @RequestMapping表示controller指定的URL
* @RequestParam:根据参数名从URL中取得参数值
*/
@Controller
public class UpDownLoad {
@RequestMapping("/login")
public String login(@RequestParam("username") String name, @RequestParam("password") String pass,
Model model) {
LoginModel newModel=new LoginModel();
newModel.setName(name);
newModel.setPas(pass);
if(newModel.login())
{
model.addAttribute("username", name);//传递参数
return "menu";
}
else
{   model.addAttribute("username", name);
return "index";
}
}
@RequestMapping("/fileupload")
public String upload(@RequestParam("image") CommonsMultipartFile image ,
HttpServletRequest request) throws IllegalStateException, IOException  {
//解析路径
String imgFolder =request.getSession().getServletContext().getRealPath("/fileupload");
//解析文件名
String imgUrl = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+image.getOriginalFilename();
//新建file对象
File targetImg = new File(imgFolder ,imgUrl);
String type=null;// 文件类型
type=imgUrl.indexOf(".")!=-1?imgUrl.substring(imgUrl.lastIndexOf(".")+1, imgUrl.length()):null;
if (type!=null)
{// 判断文件类型是否为空

if ("GIF".equals(type.toUpperCase())||"PNG".equals(type.toUpperCase())||"JPG".equals(type.toUpperCase()))
{
//判断文件是否存在
if (!targetImg.exists()){
targetImg.mkdirs();//不存在新建
}
image.transferTo(targetImg);
return "upsuccess";
}
}
return "upfail";
}
@RequestMapping("/filedownload")
public ResponseEntity<byte[]> download() throws IOException {
HttpHeaders headers = new HttpHeaders();
// String fileUrl="D:\\test.txt";
String fileUrl="D:\\test.jpg";
File file= new File(fileUrl);
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
String charset=new String(fileUrl.getBytes("utf-8"),"iso-8859-1");
headers.setContentDispositionFormData("file", charset);
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
headers, HttpStatus.CREATED);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
[/code]


2.测试

​ 图片上传:








图片下载:



文件下载:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐