上传图片

简介: 上传图片需要注意哪些:1、多图片上传2、单图片上传3、图片上传位置 4、上传图片格式限制 5、上传图片大小限制 6、图片预览7、图片上传错误8、图片的删除File file = new File(“图片路径”); if(file.

上传图片需要注意哪些:

1、多图片上传

2、单图片上传

3、图片上传位置

 4、上传图片格式限制

 5、上传图片大小限制

 6、图片预览

7、图片上传错误

8、图片的删除

File file = new File(“图片路径”);
if(file.exists()) file.delete();

 

样式一、

》 css样式

body {
margin: 20px auto;
padding: 0;
width: 580px;
font: 75%/120% Arial, Helvetica, sans-serif;
text-align:center;
}
h2 {
font: bold 190%/100% Arial, Helvetica, sans-serif;
margin: 0 0 .2em;
}
h2 em {
font: normal 80%/100% Arial, Helvetica, sans-serif;
color: #999999;
}
#largeImg {
border: solid 1px #ccc;
width: 550px;
height: 400px;
padding: 5px;
}
.thumbs img {
border: solid 1px #ccc;
width: 50px;
height: 50px;
padding: 4px;
}
.thumbs img:hover {
border-color: #FF9900;
}

#large{
position:absolute;
z-index:999;
}

<script type="text/javascript">

$(function(){

$(".thumbs a").click(function(){

var imgpath=$(this).attr("href");
var imgtittle=$(this).attr("tittle");

$("#largeImg").attr({
src:imgpath,
alt:imgtittle

});
//阻止a标签的默认行为
return false;
})

 </script>

<h2>图片预览</h2>
<p><img id="largeImg" alt="largeimage" src="img/1.jpg"/></p>
<p class="thumbs">

<a href="img/1.jpg" title="image1" ><img title="image1" src="img/1.jpg"/></a>
<a href="img/2.jpg" title="image2" ><img title="image2" src="img/2.jpg"/></a>
<a href="img/3.jpg" title="image3" ><img title="image3" src="img/3.jpg"/></a>
<a href="img/4.jpg" title="image4" ><img title="image4" src="img/4.jpg"/></a>
<a href="img/5.jpg" title="image5" ><img title="image5" src="img/5.jpg"/></a>

</p>

 

 样式二、鼠标在小图上移动会出现原图

 

 代码如下:在测试过程中发现firefox和opera对鼠标坐标不兼容,有改正,想看详细差别请看我的另一篇文章

 

<script type="text/javascript">

$(function(){

var la=$("#large");
la.hide();
$("#pic1").mousemove(function(event){
/* var event = event || window.event; 等同于下面*/
var event = event ? event:window.event;
var x = event.offsetX || event.layerX;
var y = event.offsetY || event.layerY;
la.css({
top:y,
left:x
}).html('<img src="img/4.jpg">' ).show();
}).mouseout(
function(){
la.hide();
}
)})

 </script>

预览 原图:
<img id="pic1" alt="pic" src="img/4.jpg" width="90" heigth="90">
<div id="large"></div>

 

 

 

 

 

已经编写好的代码:

准备工作需要两个jar包:commons-io-1.2.jar和commons-fileupload-1.2.jar

上传文件需要的里面的三个类可以参考我写的:http://www.cnblogs.com/keyi/p/6288752.html

 注:多文件上传用multiple属性

jsp页面

<%@page import="java.io.File"%>
<%@page import="java.text.SimpleDateFormat"%>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

//res_id 资源标识  一般是唯一的,由设定的方法获取。  这里取时间,
String res_id = (new SimpleDateFormat("yyyyMMdd")).format(new Date());

String imageInDate = (new SimpleDateFormat("yyyy-MM-dd")).format(new Date());

String imagePath="D:/Javasoftware/apache-tomcat-7.0.70/apache-tomcat-7.0.70/webapps/edu_test_copy/data/upload/images1/"+imageInDate;

File file=new File(imagePath);

%>

<!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">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
	<script type="text/javascript" src="js/jquery-1.11.1.js"></script>
	<style type="text/css">
	body {
margin: 20px auto;
padding: 0;
width: 580px;
font: 75%/120% Arial, Helvetica, sans-serif;
text-align:center;
}
h2 {
font: bold 190%/100% Arial, Helvetica, sans-serif;
margin: 0 0 .2em;
}
h2 em {
font: normal 80%/100% Arial, Helvetica, sans-serif;
color: #999999;
}
#largeImg {
border: solid 1px #ccc;
width: 550px;
height: 400px;
padding: 5px;
}
.thumbs img {
border: solid 1px #ccc;
width: 50px;
height: 50px;
padding: 4px;
}
.thumbs img:hover {
border-color: #FF9900;
}

#large{
position:absolute;	
z-index:999;
}

</style>
	
  </head>
  
  <body>
  		<h2>图片预览</h2>
<p><img id="largeImg" alt="largeimage" src=""/></p>
<p class="thumbs">
 <%
 if(file.exists()){
	File[] files = file.listFiles();
    if(files.length>0){
	  for(int i=0;i<files.length;i++){
		String fileName = files[i].getName();
		if(fileName.contains(res_id+"_2_")){
		String file_path =  "data/upload/images1/"+imageInDate+"/"+fileName;
		
		%>



<a href="<%=file_path %>" title="<%=file_path %>"><img title="<%=file_path %>" src="<%=file_path %>"/></a>
	<% 
	   }
	 }
 }
 }

  %>
  </p>
      <form action="servlet/UploadImageServlet" method="post" enctype="multipart/form-data">
     
       <input  type="file" name="file" value="文件上传"  multiple><br><br>
       <input type="hidden" name="imageInDate" value="<%=imageInDate%>">
       <input type="hidden" name="res_id" value="<%=res_id%>">
       <input  type="submit" value="提交">
     </form>
  </body>
  
 <script type="text/javascript">

$(function(){

$(".thumbs a").click(function(){

var imgpath=$(this).attr("href");
var imgtittle=$(this).attr("tittle");

$("#largeImg").attr({
src:imgpath,
alt:imgtittle

});
//阻止a标签的默认行为
return false;
})

})

 </script>
</html>

  

servlet页面

package uploadFile;

import java.awt.image.BufferedImage;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
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.FileUploadBase.SizeLimitExceededException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang.time.DateFormatUtils;

public class UploadImageServlet extends HttpServlet {

	/**
	 * Constructor of the object.
	 */

	private ServletConfig config;

	public UploadImageServlet() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html");
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		
		PrintWriter out = response.getWriter();
		//只对post提交方式有效
		String visit_from = request.getHeader("referer");
		
		ServletContext ctx=config.getServletContext();
		String temppath=ctx.getRealPath("/tempfiles");
		File tempdir=new File(temppath);
		if(!tempdir.exists()) tempdir.mkdir();
		
		DiskFileItemFactory dfif = new DiskFileItemFactory();
		//以字节为单位,默认10kb即10*1024
		dfif.setSizeThreshold(4*1024);
		dfif.setRepository(tempdir);
		
		ServletFileUpload cfu = new ServletFileUpload(dfif);
		cfu.setSizeMax(3*1024*1024);
		  List fileList = null;
		  try 
		  {
		      fileList = cfu.parseRequest(request);

		  } 
		  catch (FileUploadException e) 
		  {
			  if (e instanceof SizeLimitExceededException)
			  {
			     out.println("<script>alert('图片大小限制为"+3+"M');window.location.href='"+visit_from+"';</script>");
			     return;
			  }
			   e.printStackTrace();
		  }
		  
		  if (fileList == null || fileList.size() == 0)
		  {
			    out.println("<script>alert('请选择上传的图片文件');window.location.href='"+visit_from+"';</script>");
			    out.flush();
				out.close();
			    return;
		  } 
		
		  
		  //非文件表单元素的数据的被保存map中,可以用于获取页面传来的参数。
		  Iterator fileAgain = fileList.iterator();
		    Map paraMap = new Hashtable();
			  while (fileAgain.hasNext())
			  {
				  FileItem fileItem = null;
				  fileItem = (FileItem) fileAgain.next();
				  if (fileItem == null || fileItem.isFormField())
				  {
					 	paraMap.put(fileItem.getFieldName(), new String(fileItem.getString().getBytes("iso8859-1"), "utf-8"));
				  }
			  }
			  System.out.println(paraMap);
			   
			  //图片格式(通过格式来控制文件是图片还是其他文本)

			   Iterator fileItr = fileList.iterator();
			   BufferedImage bi = null;
			   while (fileItr.hasNext()) {
				   FileItem fileItem = null;
				   String path = null;
				   long size = 0;
				   fileItem = (FileItem) fileItr.next();
				   
				   if (fileItem == null || fileItem.isFormField()) continue;
				   
				   path = fileItem.getName();
				   size = fileItem.getSize();
				   if ("".equals(path) || size == 0) continue;
				   
				  
				   String file_name = path.substring(path.lastIndexOf("\\") + 1);
				   
				   
				   String file_type = file_name.substring(file_name.lastIndexOf(".") + 1);
				   
				   String imageType="jpg,png,gif,bmp";
				   
				   //String imageType="jpg,gif,jpeg,png,bmp";
			   
				   if(imageType.indexOf(file_type.toLowerCase() ) == -1)
				   {
					   System.out.println(visit_from);
					   out.println("<script>alert('您上传的图片格式不正确');window.location.href='"+visit_from+"';</script>");
					   out.flush();
					   out.close();
					   return;
				   }
				   
				   //保存图片
				 //  String str = (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS")).format(new Date());
				   String imageInDate = (String) paraMap.get("imageInDate");
				   String res_id = (String) paraMap.get("res_id");
				   int i=0;
				   Iterator savefileItr = fileList.iterator();
				   while (savefileItr.hasNext()) {
					   FileItem sfileItem = null;
					 
					   sfileItem = (FileItem) savefileItr.next();
					   
					   if (sfileItem == null || sfileItem.isFormField()) continue;
					   
					   path = sfileItem.getName();
					   size = sfileItem.getSize();
					   if ("".equals(path) || size == 0) continue;
					   
					  
					   String file_name1 = path.substring(path.lastIndexOf("\\") + 1);
					   String file_type1 = file_name1.substring(file_name1.lastIndexOf(".") + 1);
						
					   String savePath=ctx.getRealPath("/data/upload/images1/"+imageInDate);
						   File uploadFile = new File(savePath);  
						   if(!uploadFile.exists()) {uploadFile.mkdirs();}else{ i=uploadFile.list().length;}
						   String imgfile = savePath+ "/"+res_id+"_2_"+i+"."+file_type1;	
						   try {
							sfileItem.write(new File(imgfile));
						} catch (Exception e) {
							// TODO Auto-generated catch block
						
							e.printStackTrace();
						}
				          
				   		
					}
				   out.println("<script> var f=confirm(\"你确定继续上传吗\");if(f==true)window.location.href='"+visit_from+"';</script>");
				   
				  
				   
				   
				   
			   }
		

			   }
	


	/**
	 * The doPost method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to
	 * post.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);

	}

	/**
	 * Initialization of the servlet. <br>
	 * 
	 * @throws ServletException
	 *             if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

	public void init(ServletConfig config) throws ServletException {
		// TODO Auto-generated method stub
		this.config = config;
		 ServletContext ctx=config.getServletContext();
		 String savePath=ctx.getRealPath("/data/upload/images1");
		
		 System.out.println(savePath);

	}

}

  

 

目录
相关文章
|
存储 JavaScript 安全
阿里 OSS图片上传 —— 原生JS中使用
这是最近开发遇到的一个坑,&quot;可爱&quot;的前辈们留下来的宝贵财产,很不幸的是,一行注释都没给,所以开心(被迫)的去研究了一下文档. 然而发现官方文档又臭又长,于是自己捣鼓了下,总算是搞出来了.
1515 0
阿里 OSS图片上传 —— 原生JS中使用
|
前端开发 JavaScript UED
如何更好的去除谷歌浏览器中input自动填充背景?
如何更好的去除谷歌浏览器中input自动填充背景?
如何更好的去除谷歌浏览器中input自动填充背景?
|
Unix Linux
Touch命令使用指南:创建、更新和修改文件时间戳
Touch命令使用指南:创建、更新和修改文件时间戳
1454 0
|
监控 iOS开发 MacOS
解决启动 Parallels Desktop 之后 macOS 没声音的问题
解决启动 Parallels Desktop 之后 macOS 没声音的问题
1341 0
解决启动 Parallels Desktop 之后 macOS 没声音的问题
|
数据处理 项目管理
进度一目了然,Excel和看板的神仙联动
在项目管理中,Excel擅长结构化信息记录,但直观展示项目进度稍显不足。结合板.栗.看.板.工具,可将Excel数据同步为任务卡片,清晰显示任务状态、完成时间、负责人和优先级,实现数据与看板的双向联动,提升团队协作效率。
进度一目了然,Excel和看板的神仙联动
|
存储 安全 数据安全/隐私保护
表情包受保护无法发送怎么破解和制作gif表情包
表情包受保护无法发送怎么破解和制作gif表情包
938 0
|
Rust 并行计算 安全
Rust中的并行与并发优化:释放多核性能
Rust语言以其内存安全和高效的并发模型在并行计算领域脱颖而出。本文深入探讨了Rust中的并行与并发优化技术,包括使用多线程、异步编程、以及并行算法等。通过理解并应用这些技术,Rust开发者可以有效地利用多核处理器,提高程序的性能和响应能力。
|
存储 计算机视觉
【论文速递】WACV2023 - 循环相似注意力的小样本医学图像分割
【论文速递】WACV2023 - 循环相似注意力的小样本医学图像分割
|
人工智能 自然语言处理 关系型数据库
AI知识库问答应用:解锁智能互动的未来
函数计算 X RDS PostgreSQL,基于 LLM 构建AI知识库问答应用
1042 2
|
API 数据处理 Python
量化合约交易连接交易所API合约开发Python源码详情
# 获取特定市场的行情数据 symbol = &#39;BTC/USDT&#39; market = next(m for m in markets if m[&#39;symbol&#39;] == symbol) ticker = exchange.fetch_ticker(market) print(ticker)