Jsp+Servlet+JavaBean上传图片并显示

开发环境

1.MyEclipse 2017

2.Jdk 7.0

3.Win10

基本配置

1.依次导入commons-fileupload-1.3.3.jar、commons-io-2.6.jar两个Jar包和jquery-3.1.1.min.js,然后再创建一个upload文件夹。

配置图如下

"配置图

Tips:jar包别忘了Build Path 哦!

创建Servlet类

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
80
81
82
83
84
85
86
87
88
89
90
91
92
package com.xiaodai.server;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;


public class fileUpload extends HttpServlet {

/**
*
*/
private static final long serialVersionUID = 1L;

public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
request.setCharacterEncoding("utf-8"); // 设置编码
String fName = "";
String suffix = "";
DiskFileItemFactory factory = new DiskFileItemFactory();
String path = this.getServletContext().getRealPath("upload");
factory.setRepository(new File(path));
// 设置 缓存的大小,当上传文件的容量超过该缓存时,直接放到 暂时存储室
factory.setSizeThreshold(1024 * 1024);
// 高水平的API文件上传处理
ServletFileUpload upload = new ServletFileUpload(factory);
try {
// 可以上传多个文件
List<FileItem> list = (List<FileItem>) upload.parseRequest(request);
for (FileItem item : list) {
// 获取表单的属性名字
String name = item.getFieldName();
// 如果获取的 表单信息是普通的 文本 信息
if (item.isFormField()) {
// 获取用户具体输入的字符串 ,名字起得挺好,因为表单提交过来的是 字符串类型的
String value = item.getString();
request.setAttribute(name, value);
} else {
// 获取路径名
String value = item.getName();
// 索引到最后一个反斜杠
int start = value.lastIndexOf("\\");
// 截取 上传文件的 字符串名字,加1是 去掉反斜杠,
String filename = value.substring(start + 1);
if (filename.indexOf(".") >= 0) {
// 就截取.之前的字符串
int indexdot = filename.indexOf(".");
suffix = filename.substring(indexdot);
fName = filename.substring(0, filename.lastIndexOf("."));
Date now = new Date();
fName = fName + "_" + now.getTime();
fName = fName + suffix;
}
OutputStream out = new FileOutputStream(new File(path,fName));
request.setAttribute(name, fName);
InputStream in = item.getInputStream();
int length = 0;
byte[] buf = new byte[1024];
System.out.println("获取上传文件的总共的容量:" + item.getSize());
// in.read(buf) 每次读到的数据存放在 buf 数组中
while ((length = in.read(buf)) != -1) {
// 在 buf 数组中 取出数据 写到 (输出流)磁盘上
out.write(buf, 0, length);
}
in.close();
out.close();
}
}
} catch (FileUploadException e) {
e.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
}
request.getRequestDispatcher("filedemo.jsp").forward(request, response);
}

public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
doGet(request, response);
}

}

编辑Jsp文件

1.在WebRoot下创建一个filedemo.jsp文件

2.编辑index.jsp页面

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
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>上传文件</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<script src="../js/jquery-3.1.1.min.js"></script>
<body>
<form action="fileUpload" enctype="multipart/form-data" method="post">
图片名称:<input type="text" name="usename"> <br />
上传图片:<input type="file" id="file0" name="file1"><br />
<img src="" id="img0"><br/>
<input type="submit" value="提交" />
</form>
<script>
("#file0").change(function(){
var objUrl = getObjectURL(this.files[0]);
console.log("objUrl = " + objUrl);
if(objUrl){("#file0").attr("src", objUrl)}});
function getObjectURL(file) {
var url = null;
if (window.createObjectURL != undefined) { // basic
url = window.createObjectURL(file);
} else if (window.URL != undefined) { // mozilla(firefox)
url = window.URL.createObjectURL(file);
} else if (window.webkitURL != undefined) { // webkit or chrome
url = window.webkitURL.createObjectURL(file);
}
return url;
}
</script>
</body>
</html>

Tipa:enctype=”multipart/form-data” 必须写在form表单内

3.回到filedemo.jsp页面进行最后的编辑

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
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>显示图片</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>

<body>
<!-- 用户名称:requestScope.usename<br/> -->
<!-- 图片名称:{requestScope.file1}<br/> -->
<%-- 文件名称:${requestScope.file2}<br/> --%>
<!-- 把上传的图片显示出来 -->
<img alt="go" src="upload/<%=(String) request.getAttribute("file1")%> " style="width:500px;height:500px;"/>
</body>
</html>

快去试试吧

需要
commons-fileupload-1.3.3.jar
commons-io-2.6.jar
jquery-3.1.1.min.js
这些文件欢迎在下方留言

0%