Home >Java >javaTutorial >How to upload and display pictures in jsp

How to upload and display pictures in jsp

(*-*)浩
(*-*)浩Original
2019-05-18 21:07:417755browse

jsp上传显示图片的方法:首先创建上传JSP页面;然后创建上传图片后台处理业务“upload.jsp”;最后使用JS完成交互。

How to upload and display pictures in jsp

之前做过一个项目,有一个功能是图片上传并且展示图片,尝试过其他的方法,但会有一个问题,那就是在IE8上图片并不能下常展示,

所以便用以下方法来上传图片,很好的解决了此问题,步骤如下:

1.上传图片页面index.jsp

<%@ page language="java" import="java.util.*,java.net.URLDecoder" 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>My JSP 'index.jsp' starting page</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">
	<script  type="text/javascript" src="js/jquery-1.8.0.min.js"></script>
	<script  type="text/javascript" src="js/ajaxupload.js"></script>
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
</head>
<body>
<script type="text/javascript">
$(function(){
	//上传图片
	new AjaxUpload('#addLabProdPic', {
		action: 'upload.jsp',
		name: 'picFile',
		responseType: 'json',
		onSubmit : function(file , ext){
			if (ext && /^(jpg|png|bmp)$/.test(ext.toLowerCase())){
				this.setData({
					'picName': file
				});
			} else {
				alert("请上传格式为 jpg|png|bmp 的图片!");
				return false;				
			}
		},
		onComplete : function(file,response){
			if(response.error) {
				alert(response.error);
				return;
			}
			//alert(response.picUrl);
			show(response.picUrl);
		}		
	});
})
function show(path){
	
if(document.all)//IE
{
//path = "D:/upload/11.png";
document.getElementById("imgPreview").innerHTML="";
document.getElementById("imgPreview").style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled='true',sizingMethod='scale',src=\"" + path + "\")";//使用滤镜效果www.2cto.com  
}
else//FF
{
//path = "D:/upload/11.png";
//document.getElementById("imgPreview").innerHTML = "<img id=&#39;img1&#39; width=&#39;120px&#39; height=&#39;100px&#39; src=&#39;"+path+"&#39;/>";
document.getElementById("img1").src = path;
}
};
</script>
<h1>Ajax文件上传例子,选择图片后立即上传,无需点击上传按钮</h1>
	<button id="addLabProdPic">选择图片</button>
	<br>
	<div id="imgPreview" style=&#39;width:120px; height:100px;&#39;>
	<img id="viewImg"  width="200px" height="200px;">
	</div>
</body>
</html>

2.上传图片后台处理业务upload.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@page import="java.io.PrintWriter,java.io.File,org.apache.commons.fileupload.FileItem,org.apache.commons.fileupload.disk.DiskFileItemFactory,org.apache.commons.fileupload.servlet.ServletFileUpload" %>
<%
System.out.println("///////");
// dfif对象为解析器提供解析时的缺省的一些配置
	DiskFileItemFactory dfif = new DiskFileItemFactory();
// 创建解析器
	ServletFileUpload sfu = new ServletFileUpload(dfif);
sfu.setHeaderEncoding("utf-8");//解决了上传图片如果为中文就是乱码问题
String loadpath="D:/upload";//上传文件存放目录(此路径是将上传的文件放在本地的硬盘上)
String filName="";
try{
	// 开始解析(分析InputStream)
	// 每一个表单域当中的数据都会
	// 封装到一个对应的FileItem对象上。
	List<FileItem> items = sfu.parseRequest(request);
	for (int i = 0; i < items.size(); i++) {
		FileItem item = items.get(i);
		// 要区分是上传文件域还是普通的表单域
		if (item.isFormField()) {
					// 普通表单域
					String name = item.getString();
					filName=name;
					System.out.println("name:" + name);
				} else {
					// 上传文件域
					// ServletContext:servlet上下文对象。
					ServletContext sctx = getServletContext();
					// 获得原始的文件名
					String filename = item.getName();
			File loadFolder = new File(loadpath);
			if (!loadFolder.exists()) {
				loadFolder.mkdirs();
			}
					File file = new File(loadFolder + "\\" + filename);
					item.write(file);
				}
	}
	String result=loadpath+"/"+filName;
	PrintWriter writer = response.getWriter();
	
	writer.print("{");
	//writer.print("msg:\"文件大小:"+item.getSize()+",文件名:"+filename+"\"");
	writer.print("picUrl:\"" + result + "\"");
	writer.print("}");
	
	writer.close();
}catch(Exception e){
	e.printStackTrace();
}
%>

3.所需主要文件ajaxupload.js 

这部分缺失,导致交互出现问题,所以需要大家摸索了,加油。

The above is the detailed content of How to upload and display pictures in jsp. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn