前台jsp代码
<%@ page language="java" pageEncoding="UTF-8" contentType="text/html;charset=utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta http-equiv=Content-Type content="text/html; charset=utf-8" />
<title>单张图片上传</title>
<link rel="stylesheet" type="text/css" href="/css/upload/uploadImg.css">
<script type="text/javascript" src="/js/jquery-2.0.0.min.js"></script>
<script type="text/javascript" src="/js/layer/layer.js"></script>
<style type="text/css">
</style>
</head>
<body>
<div style="height: 500px;">
<div class="img-box">
<img src="" id="yushow"/>
<button class="btn-uploading" onclick="uploadBtn();"><i class="icon-uploading"></i>上传图片</button>
<a class="shan" onclick="deleteImg();"><img src="/images/upload/shanI.gif"></a>
</div>
<input type="file" name="file" style="display:none;" onchange="previewImg(this);" id="upload" accept="image/*"/>
</div>
</body>
<script type="text/javascript"> function uploadBtn(){
$("#upload").click();
} //图片预览
function previewImg(imgFile){
console.log(imgFile);//这里打印出是整个input标签
var extension = imgFile.value.substring(imgFile.value.lastIndexOf("."),imgFile.value.length);//扩展名
extension = extension.toLowerCase();//把文件扩展名转换为小写
if ((extension!='.jpg')&&(extension!='.gif')&&(extension!='.jpeg')&&(extension!='.png')&&(extension!='.bmp')){
layer.msg("对不起,系统仅支持标准格式的照片,请您调整格式后重新上传,谢谢 !");
$(".btn-uploading").focus();//将焦点定位在文件上传的按钮上,可以直接按确定键再次触发
}else{
var path;//预览地址
if(document.all){//IE
imgFile.select();
path = document.selection.createRange().text;
}else{//火狐,谷歌
path = window.URL.createObjectURL(imgFile.files[0]);
}
$("#yushow").attr("src",path);//设置预览地址
uploadImg(imgFile);
}
} //开始上传
function uploadImg(imgFile){
//获取图片文件
var file = imgFile.files[0];//文件对象
var name = file.name;//图片名
//var size = file.size;//图片大小
//var type = file.type;//文件类型 //检测浏览器对FileReader的支持
if(window.FileReader) {
var reader = new FileReader();
reader.onload = function(){//异步方法,文件读取成功完成时触发
var dataImg = reader.result;//文件一旦开始读取,无论成功或失败,实例的 result 属性都会被填充。如果读取失败,则 result 的值为 null ,否则即是读取的结果
syncUpload(name,dataImg);
};
reader.readAsDataURL(file);//将文件读取为 DataURL
}else {
layer.msg("浏览器不支持H5的FileReader!");
}
} function syncUpload(name,dataImg){
var imgFile = dataImg.replace(/\+/g,"#wb#");//将所有“+”号替换为“#wb#”
imgFile = imgFile.substring(imgFile.indexOf(",")+1);//截取只保留图片的base64部分,去掉了data:image/jpeg;base64,这段内容
imgFile = encodeURIComponent(imgFile);//把字符串作为 URI 组件进行编码。后台容器会自动解码一次
name = encodeURIComponent(encodeURIComponent(name));//这里对中文参数进行了两次URI编码,后台容器自动解码了一次,获取到参数后还需要解码一次才能得到正确的参数内容
var mydata = "method=uploadImg&imgFile="+imgFile+"&imgName="+name;
$.ajax({
url: "/UploadServlet",
data: mydata,
type: "post",
dataType: "json",
success: function(data){
if(data.state == 'ok'){
document.getElementById("upload").value = "";//重置文件域
layer.msg(data.msg);
}else if(data.state == 'error'){
layer.msg(data.msg);
}
}
});
} //删除图片
function deleteImg(){
$.ajax({
url: "/UploadServlet",
data: "method=deleteImg",
type:"post",
dataType: "json",
success: function(data){
if(data.state == 'ok'){
layer.msg(data.msg);
}else if(data.state == 'error'){
layer.msg(data.msg);
}
}
});
}
</script>
</html>
后台Servlet代码
package com.demo.servlet; import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLDecoder; import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import net.sf.json.JSONObject;
import sun.misc.BASE64Decoder; /**
* 文件上传Servlet
*/
@WebServlet("/UploadServlet")
public class UploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public UploadServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
String method = request.getParameter("method");
if (method != null) {
if (method.equals("uploadImg")) {
this.uploadImg(request,response);
}else if (method.equals("deleteImg")) {
this.deleteImg(request, response);
}
}else {//当不能从request中直接获取到数据的时候需要从流中读取
try {
BufferedReader br = request.getReader();
String line = null;
StringBuffer sb = new StringBuffer();
while((line = br.readLine())!=null){
sb.append(line);
}
String params = sb.toString();
if(params.contains("method")){
request.setAttribute("params", params);
if (params.contains("uploadImg")){
this.uploadImg(request,response);
} else if (params.contains("deleteImg")){
this.deleteImg(request, response);
}
return;
} else {
response.getWriter().print("missing parameter 'method'!");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.getWriter().close();
} catch (Exception e) {}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 上传图片
* @param request
* @param response
*/
private void uploadImg(HttpServletRequest request,HttpServletResponse response) {
try {
System.out.println("=================《《图片开始上传》》===================");
response.setContentType("text/html;charset=utf-8");
String imgFile = request.getParameter("imgFile");
String imgName = request.getParameter("imgName"); //request中没获取到参数时的处理
if (imgFile == null || imgName == null ) {
String params = (String)request.getAttribute("params");
if (params != null && imgFile == null && params.indexOf("imgFile=") != -1){
imgFile = params.substring(params.indexOf("imgFile=") + "imgFile=".length(), params.indexOf("&imgName="));
}else {
System.out.println("imgFile参数错误");
response.getWriter().print(JSONObject.fromObject("{'state':'error','msg':'imgFile参数错误'}").toString());
return;
}
if (params != null && imgName == null && params.indexOf("imgName=") != -1) {
imgName = params.substring(params.indexOf("imgName=") + "imgName=".length());
}else {
System.out.println("imgName参数错误");
response.getWriter().print(JSONObject.fromObject("{'state':'error','msg':'imgName参数错误'}").toString());
return;
}
}
//对参数为空进行判断
if ("".endsWith(imgFile.trim()) || "".endsWith(imgName.trim())) {
System.out.println("参数为空");
response.getWriter().print(JSONObject.fromObject("{'state':'error','msg':'参数为空'}").toString());
return;
} imgName = URLDecoder.decode(imgName,"utf-8");//前面进行了两次编码,这里需要用解码器解码一次
//String path = "/site/images"+File.separator+imgName;//Linux文件保存路径
String path = "F:\\site\\images"+File.separator+imgName;//Windows文件保存路径 //File file = new File("/site/images");
File file = new File("F:\\site\\images");
if(!file.exists() && !file.isDirectory()){//如果文件夹不存在则创建
System.out.println("文件目录不存在,开始创建");
//file.mkdirs();//生成所有目录
//file.mkdir();//生成最后一层目录
if (!file.mkdirs()) {
System.out.println("文件目录创建失败");
response.getWriter().print(JSONObject.fromObject("{'state':'error','msg':'文件目录创建失败'}").toString());
return;
}
} FileOutputStream os = new FileOutputStream(path);
imgFile = imgFile.replaceAll("#wb#", "+");
BASE64Decoder decoder = new BASE64Decoder();
byte[] b = decoder.decodeBuffer(imgFile);
for(int i=0;i< b.length;++i){
if(b[i]< 0){//调整异常数据
b[i]+=256;
}
}
InputStream is = new ByteArrayInputStream(b);
int len = 0;
while((len=is.read(b))!=-1){
os.write(b,0,len);
}
os.close();
is.close();
System.out.println("上传成功,文件保存在:"+path);
response.getWriter().print(JSONObject.fromObject("{'state':'ok','msg':'上传成功'}").toString());
} catch (Exception e) {
e.printStackTrace();
try {
response.getWriter().print(JSONObject.fromObject("{'state':'error','msg':'"+e.getMessage()+"'}").toString());
} catch (IOException e1) {
e1.printStackTrace();
}
} }
/**
* 删除图片
* @param request
* @param response
*/
private void deleteImg(HttpServletRequest request,HttpServletResponse response) {
try {
System.out.println("=================《《图片开始删除》》===================");
String path = request.getParameter("path");
if (path == null || "".endsWith(path.trim())) {
System.out.println("path参数错误");
response.getWriter().print(JSONObject.fromObject("{'state':'error','msg':'path参数错误'}").toString());
return;
}
//删除文件
File file = new File(path);
//路径存在并且为文件则进行删除
if (file.exists() && file.isFile()) {
file.delete();
System.out.println("删除成功,文件路径:"+path);
response.getWriter().print(JSONObject.fromObject("{'state':'ok','msg':'删除成功'}").toString());
}
} catch (Exception e) {
e.printStackTrace();
try {
response.getWriter().print(JSONObject.fromObject("{'state':'error','msg':'"+e.getMessage()+"'}").toString());
} catch (IOException e1) {
e1.printStackTrace();
}
}
} }
css样式表文件
.img-box{
margin:0 auto;
top:50%;
width: 500px;
height: 250px;
position:relative;
background: rgb(249,249,249);
border: 1px solid rgb(197, 190, 190);
}
.img-box img{
max-width: 100%;
max-height: 100%;
position: absolute;/*绝对定位*/
top:50%;
left: 50%;
-webkit-transform: translate(-50%,-50%); /*-webkit-是厂商前缀*/
-ms-transform: translate(-50%,-50%); /*-ms-是厂商前缀*/
transform: translate(-50%,-50%);/*translate是移动属性,两个-50%代表着像原始位置向左、向上各移动50%*/
} .btn-uploading{
width: 112px;
background-color: #3598db;
font-size: 15px;
line-height: 38px;
color: #fff;
position:absolute;
top:50%;
margin-top:-16px;
left: 50%;
margin-left: -62px;
text-align: center;
border-radius: 3px;
z-index:;
cursor: pointer;
}
.icon-uploading{
width: 27px;
height: 27px;
display: inline-block;
background: url(/images/upload//upload.png) no-repeat;
position: relative;
top:6px;
} .shan{
position: absolute;
right:2px;
bottom:5px;
width: 9px;
height: 12px;
cursor:pointer;
} button{
outline: none;
border:0 none; }
页面效果
如果想了解多张图片的上传:可参考另一篇博客:JavaScript实现多张图片上传功能