效果图如下:

                                 

代码:

注意:需要jar包:commons-fileupload-1.2.1.jar  和 commons-io-1.4.jar

index.jsp

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>添加图片</title>
<script type="text/javascript">
//打开上传页面
function openUpload(){
var win = window.showModalDialog("/upload.jsp","","dialogWidth:300px;dialogHeight:200px;scroll:no;status:no");
if(win != null){
document.getElementById("photo_id").value = win;
document.getElementById("img_id").src = "/"+win;
}
}
</script>
</head>
<body>
<h5>添加图片</h5><hr/>
<p>
上传图片:
<label>
<input type="hidden" id="photo_id" name="photo" value="images/default.gif">
<input type="button" onclick="openUpload()" value="上传图片"/><br/>
<img id="img_id" alt="" src="/images/default.gif" width="200px" height="200px">
</label>
</p>
</body>
</html>
upload.jsp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GBK">
<meta http-equiv="pragma" content="no-cache" />
<span style="color: #ff0000;"><base target="_self"></span>
<title>图片上传</title>
</head>
<body>
<h5>图片上传</h5><hr/>
<p style="color: red">${requestScope.errorMsg}</p>
<form id="form1" name="form1" action="/servlet/Upload" method="post" enctype="multipart/form-data">
<div>注:图片大小最大不能超过3M!</div>
<div>
<input type="file" name="file_upload"/>
<input type="submit" value="上传"/>
</div>
</form>
</body>
</html>
Upload.java 中的主要代码:
public class Upload extends HttpServlet {

    private String uploadPath = "aa/upload/"; // 上传文件的目录
private String tempPath = "aa/uploadtmp/"; // 临时文件目录
private String serverPath = null; private int sizeMax = 3;//图片最大上限
private String[] fileType = new String[]{".jpg",".gif",".bmp",".png",".jpeg",".ico"}; public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
response.setCharacterEncoding("utf-8"); //设置编码,方式返回的中文乱码 serverPath = getServletContext().getRealPath("/").replace("\\", "/");
//Servlet初始化时执行,如果上传文件目录不存在则自动创建
if(!new File(serverPath+uploadPath).isDirectory()){
new File(serverPath+uploadPath).mkdirs();
}
if(!new File(serverPath+tempPath).isDirectory()){
new File(serverPath+tempPath).mkdirs();
} DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(5*1024); //最大缓存
factory.setRepository(new File(serverPath+tempPath));//临时文件目录 ServletFileUpload upload = new ServletFileUpload(factory);
upload.setSizeMax(sizeMax*1024*1024);//文件最大上限 String filePath = null;
try {
List<FileItem> items = upload.parseRequest(request);//获取所有文件列表
for (FileItem item : items) {
//获得文件名,这个文件名包括路径
if(!item.isFormField()){
//文件名
String fileName = item.getName().toLowerCase(); if(fileName.endsWith(fileType[0])||fileName.endsWith(fileType[1])||fileName.endsWith(fileType[2])||fileName.endsWith(fileType[3])||fileName.endsWith(fileType[4])||fileName.endsWith(fileType[5])){
String uuid = UUID.randomUUID().toString();
filePath = serverPath+uploadPath+uuid+fileName.substring(fileName.lastIndexOf("."));
item.write(new File(filePath));
PrintWriter pw = response.getWriter();
pw.write("<script>alert('上传成功');window.returnValue='"+uploadPath+uuid+fileName.substring(fileName.lastIndexOf("."))+"';window.close();</script>");
pw.flush();
pw.close();
}else{
request.setAttribute("errorMsg", "上传失败,请确认上传的文件存在并且类型是图片!");
request.getRequestDispatcher("/upload.jsp").forward(request,response);
}
}
}
} catch (Exception e) {
e.printStackTrace();
request.setAttribute("errorMsg", "上传失败,请确认上传的文件大小不能超过"+sizeMax+"M");
request.getRequestDispatcher("/upload.jsp").forward(request,response);
}
} }
 <p style="color: red">${requestScope.errorMsg}</p>

表示变量的作用域,一共4种。

pageScope: 表示变量只能在本页面使用。

requestScope:表示变量能在本次请求中使用。

sessionScope:表示变量能在本次会话中使用。

applicationScope:表示变量能在整个应用程序中使用。

源码下载地址:http://download.csdn.net/detail/u011518709/7885625

common-fileupload上传图片并显示图片的更多相关文章

  1. COS上传图片和显示图片

    写这篇文章之前,我也是刚刚实现COS上传和显示图片.我百度了好多相关文章,COS上传图片成功的文章不少,上传后显示图片的文章几乎没有.于是写一篇记录下. COS上传图片推荐链接:https://blo ...

  2. springmvc上传图片并显示图片--支持多图片上传

    实现上传图片功能在Springmvc中很好实现.现在我将会展现完整例子. 开始需要在pom.xml加入几个jar,分别是: <dependency> <groupId>comm ...

  3. javaweb中上传图片并显示图片,用我要上传课程信息(里面包括照片)这个例子说明

    原理:  从客户端上传到服务器                照片——文件夹——数据库 例如:桌面一张照片,在tomacat里创建upload文件夹,把桌面照片上传到upload文件夹里,并且把照片的 ...

  4. input[type="file"]上传图片并显示图片

    <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...

  5. Java web项目 上传图片保存到数据库,并且查看图片,(从eclipse上移动到tomact服务器上,之路径更改,包括显示图片和导出excel)

    //项目做完之后,在本机电脑运行完全正常,上传图片,显示图片,导出excel,读取excel等功能,没有任何问题,但是,当打成war包放到服务器上时,这些功能全部不能正常使用. 最大的原因就是,本机测 ...

  6. 02-20 winform 上传图片并读取图片

    建立一个windows窗体应用程序,在form1界面中拖入两个按钮和一个pictureBox,通过输入输出流来上传图片和显示图片.需要添加一下openFileDialog1. 界面如下: 在cs中写上 ...

  7. 关于百度world 编辑器改变上传图片的保存路径图片不显示的问题

    在ueditor.mini for asp.net 中,将上传的图片保存的路径更改了,可图片在 world 编辑器中不显示,但却可以上传到指定的保存目录下,解决这个问题的方法 是: 在udditor_ ...

  8. 基于ASP.Net +easyUI框架上传图片,实现图片上传,提交表单

    <body> <link href="../../Easyui/themes/easyui.css" rel="stylesheet" typ ...

  9. 使用ajax上传图片,支持图片即时浏览,支持js图片压缩后上传给服务器

    使用ajax上传图片,支持图片即时浏览,支持js图片压缩后上传给服务器 ajax上传主要使用了 var reader = new FileReader() 此方法 js图片压缩主要是利用canvas进 ...

随机推荐

  1. c# 中的 protected internal 如何在 vc.net 中实现

    c# 中有 protected internal 的复合访问属性, 保证assembly内部访问,以及外部的派生类访问 vc.net 中无法直接写上 protected internal, 其对应的写 ...

  2. 反射记录点滴——Field

    反射记录点滴 1. 反射获取类的属性 Class.getDeclareFileld(String name) 返回一个Filed对象,该对象反映此Class对象所表示的类或接口的指定已声明字段. Cl ...

  3. Centos 7.x 搭建 Zabbix3.4

    前提要安装了LAMP(官方推荐环境) LNMP也可以 一.安装.配置Zabbix3.4 1:安装zabbix_RPM包 rpm -i https://repo.zabbix.com/zabbix/3. ...

  4. zoj3765Lights(splay)

    链接 splay的增删改操作. 刚开始对于某段区间首先有了lazy标记时,把其左右孩子给交换了,导致在pushup时又交换了一次而debug了n久. #include <iostream> ...

  5. setTimeout的核心原理和巧用

    你所不了解的setTimeout 发表于 2015年11月23日 by 愚人码头 被浏览 14,756 次 分享到: 0 小编推荐:掘金是一个高质量的技术社区,从 ECMAScript 6 到 Vue ...

  6. datetimepicker 插件位置问题解决经验

    使用dadetimepicker进行时间选择是个很不错的选择,但是美中不足的是该插件在chrome中显示弹框的时候有时会出现位置错位的现象,而在IE中则没有这种现象,视图如图1 图1 查阅了网上的资料 ...

  7. AJPFX总结hashmap和hashtable的区别

    Hashtable和HashMap类有三个重要的不同之处.第一个不同主要是历史原因.Hashtable是基于陈旧的Dictionary类的,HashMap是Java 1.2引进的Map接口的一个实现. ...

  8. 在Window上用cmd创建.htaccess文件

    Windows 图形下不能直接建立空名字的文件,所以没法直接创建.htaccess文件,不过可以通过命令行创建: cd /path/to/your/dir/ type nul>.htaccess ...

  9. 安卓4.4不支持touchend事件解决办法

    最近的项目要求兼容到OPPO A31这款手机,这款手机是安卓4.4,调试时遇到了touch手指不能滑动页面切换的问题,最终解决通过在touchstart事件里面加上一个 event.preventDe ...

  10. 涉及到弹出层的opacity样式问题

    最近遇到一个弹出层在Chrome中重复的问题,观察发现是opacity引起的以下是代码及现象<!DOCTYPE html><html> <head>         ...