首先,操练了很久这个功能,差点给我干废,终于搞好了,所以给大家分享一下,之前找了很多例子参考,但是均有些问题,所以把我这个成品发上来。(也有很多摘录别人的)。
然后,现在网上很多例子都是半成品或者是不靠谱的,我搜索很多颇有感触,太坑人了,我这个是成品直接发上来 经过测试,没问题,pc端也可以用。安卓ios都可以选择多少张图片上传。
后台:java (SSH)
前台:h5 js (有个jquery的jar包需要引入)
这里分享几张成品效果图把。
这里是手机上传的,
pc端可以拖拽到里面,也可以上传,点击选取文件时自动找file 。h5自带功能,手机直接提示找相册或者拍照or视频。然后选取即可 。
/**
* 这里我先把html 怼上来 , 放在pc页面可以拖拽,放在手机就不能拖拽了,我给删掉了 , 若有需要自己再加吧 。移动端没有拖拽
* ~~要注意:form表单里的action。 我加了注释了 在上面一行。(ps:就一个斜杠“/” ,我搞了一个星期不知道哪里出的错。。。很尴尬,主要是没有错误信息 )
*/
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<title>图片上传 </title>
</head>
<link rel="stylesheet" href="css/demo.css" type="text/css" />
<style>
.upload_box{width:800px; margin:1em auto;}
.upload_choose{padding:1em;}
.upload_drag_area{display:inline-block; width:60%; padding:4em 0; margin-left:.5em; border:1px dashed #ddd; background:#fff url(./drag.png) no-repeat 20px center; color:#999; text-align:center; vertical-align:middle;}
.upload_drag_hover{border-color:#069; box-shadow:inset 2px 2px 4px rgba(0, 0, 0, .5); color:#333;}
.upload_preview{border-top:1px solid #bbb; border-bottom:1px solid #bbb; background-color:#fff; overflow:hidden; _zoom:1;}
.upload_append_list{height:300px; position:relative;}
.upload_delete{margin-left:2em;}
.upload_image{max-height:250px; padding:5px;}
.upload_submit{padding-top:1em; padding-left:1em;}
.upload_submit_btn{display:none; height:32px; font-size:14px;}
.upload_loading{height:250px; background:url(/study/image/preload.gif) no-repeat center;}
.upload_progress{display:none; padding:5px; border-radius:10px; color:#fff; background-color:rgba(0,0,0,.6); position:absolute; left:25px; top:45px;}
</style>
<body>
<div id="main">
<div id="body" class="light">
<div id="content" class="show">
<h3>展示</h3>
<div class="demo"> <!--本地测试 api前面不加/ --api/CarloandApply.action -->
<form id="uploadForm" action="/api/CarloandApply.action" method="post" enctype="multipart/form-data"><!--api/CarloandApply -->
<div class="upload_box">
<div class="upload_main">
<div class="upload_choose">
<font color="#ff8080"><input type="file" id="fileImage" size="30" name="file" multiple=""></font><!-- 原name=fileselect[] -->
<!-- <span id="fileDragArea" class="upload_drag_area">或者将图片拖到此处</span> 不注释即可用拖拽功能 (搭配js)-->
<br/>
<input type="text" name="sessionid1" id="setSessid" value="" />
<input type="text" name="cno1" id="setCno" value=""/>
</div>
<div id="preview" class="upload_preview"></div>
</div>
<div class="upload_submit">
<button type="button" id="fileSubmit" class="upload_submit_btn">确认上传图片</button>
</div>
<div id="uploadInf" class="upload_inf"></div>
</div>
</form>
</div>
</div>
</div>
</div>
<script src="js/jquery-1.11.3.min.js"></script>
<script src="js/zxxFile.js"></script>
<script src="js/mui.min.js "></script>
<script src="js/appconfig.js" type="text/javascript" charset="utf-8"></script>
<script>
var params = {
fileInput: $("#fileImage").get(0),
dragDrop: $("#fileDragArea").get(0),
upButton: $("#fileSubmit").get(0),
url: $("#uploadForm").attr("action"),
filter: function(files) {
var arrFiles = [];
for (var i = 0, file; file = files[i]; i++) {
if (file.type.indexOf("image") == 0) {
if (file.size >= 2560000) {
alert('您这张"'+ file.name +'"图片大小过大,应小于2.5MB');
} else {
arrFiles.push(file);
}
} else {
alert('文件"' + file.name + '"不是图片。');
}
}
return arrFiles;
},
onSelect: function(files) {
//得到id
//var sessionid=localStorage.getItem("sessionid");
//把id赋值到input
//$('#setSessid').val(sessionid);
//得到Cno
//var cno=localStorage.getItem("cno");
//把cno赋值到input
//$('#setCno').val(cno);
var html = '', i = 0;
$("#preview").html('<div class="upload_loading"></div>');
var funAppendImage = function() {
file = files[i];
if (file) {
var reader = new FileReader()
reader.onload = function(e) {
html = html + '<div id="uploadList_'+ i +'" class="upload_append_list"><p><strong>' + file.name + '</strong>'+
'<a href="javascript:" class="upload_delete" title="删除" data-index="'+ i +'">删除</a><br />' +
'<img id="uploadImage_' + i + '" src="' + e.target.result + '" class="upload_image" /></p>'+
'<span id="uploadProgress_' + i + '" class="upload_progress"></span>' +
'</div>';
i++;
funAppendImage();
}
reader.readAsDataURL(file);
} else {
$("#preview").html(html);
if (html) {
//删除方法
$(".upload_delete").click(function() {
ZXXFILE.funDeleteFile(files[parseInt($(this).attr("data-index"))]);
return false;
});
//提交按钮显示
$("#fileSubmit").show();
} else {
//提交按钮隐藏
$("#fileSubmit").hide();
}
}
};
funAppendImage();
},
onDelete: function(file) {
$("#uploadList_" + file.index).fadeOut();
},
onDragOver: function() {
$(this).addClass("upload_drag_hover");
},
onDragLeave: function() {
$(this).removeClass("upload_drag_hover");
},
onProgress: function(file, loaded, total) {
var eleProgress = $("#uploadProgress_" + file.index), percent = (loaded / total * 100).toFixed(2) + '%';
eleProgress.show().html(percent);
},
onSuccess: function(file, response) {
$("#uploadInf").append("<p>上传成功</p>");
},
onFailure: function(file) {
$("#uploadInf").append("<p>图片" + file.name + "上传失败!</p>");
$("#uploadImage_" + file.index).css("opacity", 0.2);
},
onComplete: function() {
//提交按钮隐藏
$("#fileSubmit").hide();
//file控件value置空
$("#fileImage").val("");
$("#uploadInf").append("<p>当前图片全部上传完毕,可继续添加上传。</p>");
}
};
ZXXFILE = $.extend(ZXXFILE, params);
ZXXFILE.init();
</script>
</body>
</html>
/**
* 这里是 js的,是从网上一个大神手里拿下来的框架,大神自己编写的。很厉害。旧式ajax。我也看不明白,但知道大概意思
* 要注意的是下方formdata来append追加的,不然后台file是null 。 这里搞了很久。查阅了很多。
*/
/*
* zxxFile.js 基于HTML5 文件上传的核心脚本 http://www.zhangxinxu.com/wordpress/?p=1923
* by zhangxinxu 2011-09-12
*/
var ZXXFILE = {
fileInput: null, //html file控件
dragDrop: null, //拖拽敏感区域
upButton: null, //提交按钮
url: "", //ajax地址
fileFilter: [], //过滤后的文件数组
filter: function(files) { //选择文件组的过滤方法
return files;
},
onSelect: function() {}, //文件选择后
onDelete: function() {}, //文件删除后
onDragOver: function() {}, //文件拖拽到敏感区域时
onDragLeave: function() {}, //文件离开到敏感区域时
onProgress: function() {}, //文件上传进度
onSuccess: function() {}, //文件上传成功时
onFailure: function() {}, //文件上传失败时,
onComplete: function() {}, //文件全部上传完毕时
/* 开发参数和内置方法分界线 */
//文件拖放
funDragHover: function(e) {
e.stopPropagation();
e.preventDefault();
this[e.type === "dragover"? "onDragOver": "onDragLeave"].call(e.target);
return this;
},
//获取选择文件,file控件或拖放
funGetFiles: function(e) {
// 取消鼠标经过样式
this.funDragHover(e);
// 获取文件列表对象
var files = e.target.files || e.dataTransfer.files;
//继续添加文件
this.fileFilter = this.fileFilter.concat(this.filter(files));
this.funDealFiles();
return this;
},
//选中文件的处理与回调
funDealFiles: function() {
for (var i = 0, file; file = this.fileFilter[i]; i++) {
//增加唯一索引值
file.index = i;
}
//执行选择回调
this.onSelect(this.fileFilter);
return this;
},
//删除对应的文件
funDeleteFile: function(fileDelete) {
var arrFile = [];
for (var i = 0, file; file = this.fileFilter[i]; i++) {
if (file != fileDelete) {
arrFile.push(file);
} else {
this.onDelete(fileDelete);
}
}
this.fileFilter = arrFile;
return this;
},
//文件上传
funUploadFile: function() {
var self = this;
if (location.host.indexOf("sitepointstatic") >= 0) {
//非站点服务器上运行
return;
}
for (var i = 0, file; file = this.fileFilter[i]; i++) {
(function(file) {
var xhr = new XMLHttpRequest();
if (xhr.upload) {
// 上传中
xhr.upload.addEventListener("progress", function(e) {
self.onProgress(file, e.loaded, e.total);
}, false);
// 文件上传成功或是失败
xhr.onreadystatechange = function(e) {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
alert("成功图片="+xhr.status);
self.onSuccess(file, xhr.responseText);
self.funDeleteFile(file);
if (!self.fileFilter.length) {
//全部完毕
self.onComplete();
}
} else {
alert("失败图片="+xhr.status);
self.onFailure(file, xhr.responseText);
}
}
};
// 开始上传
xhr.open("POST", self.url, true);
xhr.setRequestHeader("X_FILENAME", encodeURIComponent(file.name));
var formdata = new FormData(); //转换成formdata ,后台才可接收
//formdata.append("cno",88888); //测试时候,88888为文件夹名字
//$('#setSessid').val(localStorage.getItem('sessionid'));
//$('#setCno').val(localStorage.getItem('cno'));
//alert($('#setSessid').val());
formdata.append("sessionid",localStorage.getItem('sessionid')); // $('#setSessid').val()
formdata.append("cno",localStorage.getItem('cno')); //$('#setCno').val()
formdata.append("file",file);
formdata.append("fname",file.name);
alert("这里是formdata="+localStorage.getItem('sessionid'));//因为是手机上传,localStorage.getItem('sessionid')只能在手机使用
xhr.send(formdata);
//xhr.send(file);
}
})(file);
}
},
init: function() {
var self = this;
if (this.dragDrop) {
this.dragDrop.addEventListener("dragover", function(e) { self.funDragHover(e); }, false);
this.dragDrop.addEventListener("dragleave", function(e) { self.funDragHover(e); }, false);
this.dragDrop.addEventListener("drop", function(e) { self.funGetFiles(e); }, false);
}
//文件选择控件选择
if (this.fileInput) {
this.fileInput.addEventListener("change", function(e) { self.funGetFiles(e); }, false);
}
//上传按钮提交
if (this.upButton) {
this.upButton.addEventListener("click", function(e) { self.funUploadFile(e); }, false);
}
}
};
/**
* 接下来是最主要后台 ,用于提交的,走的是struts2提交的,配置等会在最后我发一下,就几句话。
* 这里要注意的:注释的一堆logger请无视,当时测试打印log费死劲了,因为我不是专门做手机的,比较业余,没有连上真机测试的软件,所以这里也不报错,也显示提交成功,也没啥问题 。搞了很久
*/
package com.yxd.api.action;
import java.io.Console;
import java.io.File;
import java.io.IOException;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.impl.Log4JLogger;
import org.apache.struts2.ServletActionContext;
import org.junit.runner.Request;
import org.apache.log4j.Logger;
import com.opensymphony.xwork2.ActionContext;
import com.yxd.api.wervice.MySessionContext;
import com.yxd.common.base.BaseAction;
import com.yxd.common.utils.Guid;
import com.yxd.manage.model.AgentApply;
import com.yxd.manage.model.LoanApplyImgfile;
import com.yxd.manage.model.ProductLoandApply;
import com.yxd.manage.model.YxdNews;
import com.yxd.manage.model.YxdUser;
import com.yxd.manage.model.YxdUseraccount;
import com.yxd.manage.service.AgentApplyService;
import com.yxd.manage.service.LoanApplyImgfileService;
import com.yxd.manage.service.ProductLoandApplyService;
import com.yxd.manage.service.YxdUserService;
import com.yxd.web.action.RegistAction;
public class ApiLoandApply extends BaseAction{
//log
private Logger logger = Logger.getLogger(ApiLoandApply.class);
//public static org.apache.log4j.Logger log= org.apache.log4j.Logger.getLogger("ApiLoandApply.class");
private SimpleDateFormat sdF=new SimpleDateFormat("yyyyMMdd");
@Resource
private YxdUserService yxdUserService;
@Resource
private LoanApplyImgfileService loanApplyImgfileService;
@Resource
private ProductLoandApplyService productLoandApplyService;
@Resource
private AgentApplyService agentApplyService;
private Object rest;
private String sessionid; //用户id
private String cguid;
private String cno; //文件夹编号
private int istutas; //0 待检查 1正在审核 2审核通过 3 审核失败
private Date cuploaddate;//上传时间
private Date chickdate; //审核时间
private YxdUser cuserid; //用户id(代理人)
private File file;// 实际上传文件
private String[] uploadContentType; // 文件的内容类型
private String[] uploadFileName; // 上传文件名
// 上面这些属性,有很多是别的方法的,在这里我把别的方法给删掉了,但是上面没有删,
/**
* 车贷代理人 上传车贷图片
* @throws IOException
* */
public String carloandApply(){
// logger.debug("debug进的方法");
// logger.info("info进的方法");
//获取当前用户id
String cuserguid=null;
if(sessionid!=null&&sessionid.trim().length()>0){
logger.debug("sessionid="+sessionid);
HttpSession Sess = MySessionContext.getSession(sessionid);
if(Sess!=null){
YxdUser yu=(YxdUser)Sess.getAttribute("yxdUser");
if(yu!=null&&yu.getCguid()!=null&&yu.getCguid().length()>0){
cuserguid=yu.getCguid();
}
}
}
//logger.error(this.httpSession.getAttribute("sessionid"));
// String cGuid = Guid.newGuid();//生成ID
//String cuserguid = httpServletRequest.getParameter("sessionid");
if(cuserguid!=null&&cuserguid.trim().length()>0){
String sqla="select cguid,'' from product_loand_apply where cuserguid='"+cuserguid+"'";
List<Object[]> listms=agentApplyService.queryBySql(sqla);
if(listms!=null&&listms.size()>0){
String cid=agentApplyService.queryBySql(sqla).get(0)[0].toString();//得到cguid
//图片上传
//String realpath = ServletActionContext.getServletContext().getRealPath("/"+"applyimg");//获取服务器路径 getRealPath("http://youxiandai.cn/applyimg")
if(file!=null){ //原 upload!=null
// logger.debug("file="+file);
// logger.info("file="+file);
File target = new File( this.servletContext.getRealPath("/")+"applyimg/"+httpServletRequest.getParameter("cno"));//原realpath
// logger.debug("target="+target);
//logger.info("target="+target);
if(!target.exists()){ //判断有没有文件夹
target.mkdirs(); //新建target文件夹
}
File savefile = new File(target+"/"+httpServletRequest.getParameter("fname"));//服务器路径+图片名字
// logger.debug("savefile="+savefile);
// logger.info("savefile="+savefile);
try{
FileUtils.copyFile(file, savefile); //把file文件,复制到savefile路径里
}catch(Exception e){
e.printStackTrace();
}
rest=1;//保存成功
//ActionContext.getContext().put("message","文件上传成功");
}else{
rest=2; //没有图片
}
}
}else{
rest=4;//未登录
}
return SUCCESS;
}
public String getSessionid() {
return sessionid;
}
public void setSessionid(String sessionid) {
this.sessionid = sessionid;
}
public String getCguid() {
return cguid;
}
public void setCguid(String cguid) {
this.cguid = cguid;
}
public String getCno() {
return cno;
}
public void setCno(String cno) {
this.cno = cno;
}
public String getImgurl() {
return imgurl;
}
public void setImgurl(String imgurl) {
this.imgurl = imgurl;
}
public int getIstutas() {
return istutas;
}
public void setIstutas(int istutas) {
this.istutas = istutas;
}
public Date getCuploaddate() {
return cuploaddate;
}
public void setCuploaddate(Date cuploaddate) {
this.cuploaddate = cuploaddate;
}
public Date getChickdate() {
return chickdate;
}
public void setChickdate(Date chickdate) {
this.chickdate = chickdate;
}
public YxdUser getCuserid() {
return cuserid;
}
public void setCuserid(YxdUser cuserid) {
this.cuserid = cuserid;
}
public Object getRest() {
return rest;
}
public void setRest(Object rest) {
this.rest = rest;
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
public ProductLoandApply getNo() {
return no;
}
public void setNo(ProductLoandApply no) {
this.no = no;
}
public LoanApplyImgfile getCnoid() {
return cnoid;
}
public void setCnoid(LoanApplyImgfile cnoid) {
this.cnoid = cnoid;
}
public String getCuserno() {
return cuserno;
}
public void setCuserno(String cuserno) {
this.cuserno = cuserno;
}
public String[] getUploadContentType() {
return uploadContentType;
}
public void setUploadContentType(String[] uploadContentType) {
this.uploadContentType = uploadContentType;
}
public String[] getUploadFileName() {
return uploadFileName;
}
public void setUploadFileName(String[] uploadFileName) {
this.uploadFileName = uploadFileName;
}
}
/**
* struts2 的配置啦,几句话
* ~~
*/
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<package name="carloandApplyApi" namespace="/api" extends="struts2" >
<!-- 车贷信息图片提交-->
<action name="CarloandApply" class="项目地址" method="carloandApply">
<result name="success" type="json">
<param name="root">rest</param>
</result>
</action>
</package>
</struts>