多文件和多图片上传

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_32079585/article/details/62044844
其实想要实现多文件上传,最好的方式就是采用ajax异步上传(其实质上是多次请求单文件上传的action)
1、第一种方式:首先来个简单的jQueryajax实现的方式(以同时上传两个文件为例)
前台页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script type="text/javascript" src="jquery-1.7.2.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script type="text/javascript">
$(function(){
alert("jquery");
$("#shan").click(function(){
alert("点击");
var url="upload";
var args={"time":new Date() };
ajaxform('yuyu',url,args);
ajaxform('yuyu2',url,args);
});
function ajaxform(id,url,args){
$("#"+id).ajaxSubmit({
type: "POST",
url: "upload",
data: args,
dataType: "json",
success: function(data){
if(data!=null){
alert("您的信息已上传成功");
// window.location="showProducts";//跳转到相应的页面 或者action
}
else
alert("您的信息提交失败,请重新操作");
}
});
}
});

</script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form id="yuyu" enctype="multipart/form-data">
商品图片:<input type="file" name="wj"/><br>
商品名称:<input type="text" name="wjName"/>
商品描述:<input type="text" name="wjDesc"/>
</form>
<form id="yuyu2" enctype="multipart/form-data">
商品图片:<input type="file" name="wj"/><br>
商品名称:<input type="text" name="wjName"/>
商品描述:<input type="text" name="wjDesc"/>
</form>
<input type="button" value="提交" id="shan"/>

</body>
</html>
后台代码(处理单文件的):
public void update() throws Exception {
//修改文件名
wjFileName=new Date().getTime()+wjFileName;
System.out.println(wjContentType);
System.out.println(wjFileName);
System.out.println(wjDesc);
System.out.println(wjName);
ServletContext servletContext=ServletActionContext.getServletContext();
String path=servletContext.getRealPath("/images/"+wjFileName);//文件最终要上传到的路径
FileOutputStream out=new FileOutputStream(path);
FileInputStream in=new FileInputStream(wj);
byte[]buffer=new byte[1024];
int len=0;
while((len=in.read(buffer))!=-1){
out.write(buffer,0,len);
}
out.close();
in.close();
String name=wjName;
String desc = wjDesc;
String image = servletContext.getContextPath() + "/images/"
+ wjFileName;
Product product = new Product(null, name, desc, 0, null, image);
productService.saveProduct(product);
ObjectMapper mapper = new ObjectMapper();
String result = mapper.writeValueAsString(wj);
HttpServletResponse response = ServletActionContext.getResponse();
response.setContentType("text/javascript");
response.setCharacterEncoding("UTF-8");

response.getWriter().print(result);

}
查看效果:



2、第二种方式:利用extjs+swfupload插件实现
前端关键代码:
<%@ page contentType="text/html;charset=gb2312" language="java"%>
<html>
<head>
<title>swf 上传</title>
<link rel="stylesheet" type="text/css"
href="js/css/ext-all.css" />
</head>

<body>
<script type="text/javascript" src="js/ext-base.js"></script>
<script type="text/javascript" src="js/ext-all.js"></script>
<script src="swf/swfupload.js" type="text/javascript"></script>
<script src="swf/swfupload.speed.js" type="text/javascript"></script>
<script src="swf/mode.js" type="text/javascript"></script>
<script src="swf/handlers.js" type="text/javascript"></script>
<script type="text/javascript" src="js/prototype/prototype.js"></script>
<script type="text/javascript" src="js/bramus/jsProgressBarHandler.js"></script>
<script type="text/javascript">
// 允许上传文件的全部大小
var limtallsize=50000000;

function UploadGrid()
{
var mine=this;
var states=[{v:-1,t:'等待'},{v:0,t:'就绪'},{v:1,t:'上传中'},{v:2,t:'停止'},{v:3,t:'成功'},{v:4,t:'失败'}];
function statesRender(v)
{
for(var i=0;i<states.length ;i++)
{
if(states[i].v==v)
{
return states[i].t;
}
}
}
function rateRender(value, metaData, record, rowIndex, cellIndex, store)
{
v=value?value:0;
//return "<table border='0' cellpadding='0' cellspacing='0' width='100%' height='100%'><tr><td bgcolor='#0000FF' height='100%' align='center' width='"+v+"%'><font color='white'>"+v+"%</font></td><td></td></tr></table>";
//setProgress(v);
return "<span id=\"element6_"+record.data.id+"\" rate=\""+v+"\"></span>";
}
var rn=new Ext.grid.RowNumberer();
var sm = new Ext.grid.CheckboxSelectionModel({singleSelect:false});
var cm = new Ext.grid.ColumnModel([
rn,
sm,
{header:'文件名称',dataIndex:'fileName',menuDisabled:true,width: 100},
{header:'大小' ,dataIndex:'fileSize',menuDisabled:true,width: 100},
{header:'进度' ,dataIndex:'rate',menuDisabled:true,width: 180,renderer:rateRender},
{header:'速度' ,dataIndex:'speed',menuDisabled:true},
{header:'状态' ,dataIndex:'state',menuDisabled:true,renderer:statesRender}
]);

this.ds = new Ext.data.Store({
proxy: new Ext.data.HttpProxy({url:'test!query.action',method:'post'}),
remoteSort:false,
reader: new Ext.data.JsonReader(
{totalProperty:'records',root:'root'},
[
{name: 'id'},
{name: 'fileName'},
{name: 'code'},
{name: 'fileSize'},
{name: 'rate'},
{name: 'speed'},
{name: 'state'}
])
});
var RC=Ext.data.Record.create([
{name: 'id', mapping: 'id'},
{name: 'code', mapping: 'code'},
{name: 'fileName', mapping: 'fileName'},
{name: 'fileSize', mapping: 'fileSize'},
{name: 'rate', mapping: 'rate'},
{name: 'speed', mapping: 'speed'}
]);
this.grid = new Ext.grid.GridPanel({
ds: mine.ds,
cm: cm,
sm: sm,
anchor:'100%',
loadMask:{msg:'数据加载中...'},
viewConfig:{forceFit:true},
height:300,
width :600,
tbar:[{id:'spanSWFUploadButton',text:'-'},'-'],
listeners:{
render:function()
{
// ytb-sep
var cmp=Ext.getCmp("spanSWFUploadButton");
var pcont=cmp.getEl().parent();
pcont.update("<span id='spanSWFUploadButton' class='blank'></span>");
var swfu = new SWFUpload({
upload_url : "upload.action",
post_params : {
"god" : "god","uid" : "u"
},

flash_url : "swf/swfupload.swf",
button_placeholder_id : "spanSWFUploadButton",
button_image_url : "swf/bt.png",
button_text_right_padding : 100,
button_width: 61,
button_height : 22,
button_action : SWFUpload.BUTTON_ACTION.SELECT_FILES,
// handler here
swfupload_loaded_handler : Handlers.swfUploadLoaded,
file_queued_handler : Handlers.fileQueued,
file_queue_error_handler : Handlers.fileQueueError,
upload_progress_handler : Handlers.uploadProgress,
upload_error_handler : Handlers.uploadError,
upload_success_handler : Handlers.uploadSuccess
});
swfu.grid=mine.grid;
swfu.ds=mine.ds;
swfu.RC=RC;
}
}
});
}

Ext.onReady(function(){
Ext.QuickTips.init();
Ext.form.Field.prototype.msgTarget = 'side';
Ext.BLANK_IMAGE_URL ='../../images/s.gif';
var grid=new UploadGrid();
var win = new Ext.Window({
title:'上传表格测试',
el:'panel',
width:620,
height:350,
closeAction:'hide',//关闭窗口时渐渐缩小
plain: true,
items:[grid.grid],
buttons: [{
text:'Submit',
disabled:true
},{
text: 'Close',
handler: function(){
win.hide();
}
}]
});
win.show(this);
})
</script>
<div id="panel"></div>
</body>
</html>

后台文件处理代码(虽然是多文件上传,但我这里采用的是异步请求的方式,所以后台用单文件处理的代码完全不用动)
public String execute()
{
// String s = (String)ServletActionContext.getRequest().getParameter("god");
// String s2 = (String)ServletActionContext.getRequest().getParameter("uid");
if (Filedata != null && Filedata.length() > 0)
{
// 群组名字作为最后的文件夹
String groupFileName = "haoba";
String uploadPath = ServletActionContext.getServletContext()
.getRealPath(basePath+"\\"+groupFileName);
File path = new File(uploadPath);
if (!path.exists())
{
path.mkdirs();
}else{
//文件已存在
//FiledataFileName
}
String newPath = uploadPath +"\\"+FiledataFileName;
Filedata.renameTo(new File(newPath));
// 保存到数据库中的路径
// String savePath = basePath+"\\"+groupFileName+"\\"+FiledataFileName;
}

return null;
}
效果展示:

这里会发现,异步批量上传文件,实际上就是多次请求单文件上传的那个后台action而已,没有什么神秘的。
3、批量上传图片并加预览功能(其实道理都是相同的)
这里只展示下效果吧

如有问题请直接联系本人qq:1913284695
阅读更多
换一批

没有更多推荐了,返回首页