上传图片
上传图片需要注意哪些:
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);
}
}