首先创建解决方案,添加jquery的js和一些资源文件(如图片和进度条显示等):
1
2
3
4
5
jquery-1.3.2.min.js
jquery.uploadify.v2.1.0.js
jquery.uploadify.v2.1.0.min.js
swfobject.js
uploadify.css
1、页面的基本代码如下
这里用的是aspx页面(html也是也可的)
页面中引入的js和js函数如下:
1
2
3
4
5
6
7
<script src="js/jquery-1.3.2.min.js" type="text/javascript"></script>
<script src="js/jquery.uploadify.v2.1.0.js" type="text/javascript"></script>
<script src="js/jquery.uploadify.v2.1.0.min.js" type="text/javascript"></script>
<script src="js/swfobject.js" type="text/javascript"></script>
<link href="css/uploadify.css" rel="stylesheet" type="text/css" />
</script>
js函数:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<script type="text/javascript">
$(document).ready(function () {
$("#uploadify").uploadify({
'uploader': 'image/uploadify.swf', //uploadify.swf文件的相对路径,该swf文件是一个带有文字BROWSE的按钮,点击后淡出打开文件对团答话框
'script': 'Handler1.ashx',//script : 后台处理程序的相对路径
'cancelImg': 'image/cancel.png',
'buttenText': '请选择文件',//浏览按钮的文本,默认值:BROWSE。
'sizeLimit':999999999,//文件大小显示
'floder': 'Uploader',//上传文件存放的目录
'queueID': 'fileQueue',//文件队列的ID,该ID与存放文件队列的div的ID一致
'queueSizeLimit': 120,//上传文件个数限制
'progressData': 'speed',//上传速度显示
'auto': false,//是否自动上传
'multi': true,//是否多文件上传
//'onSelect': function (e, queueId, fileObj) {
//alert("唯一标识:" + queueId + "\r\n" +
// "文件名:" + fileObj.name + "\r\n" +
// "文件大小:" + fileObj.size + "\r\n" +
// "创建时塌磨慧间:" + fileObj.creationDate + "\r\n" +
// "最后修改时间:" + fileObj.modificationDate + "\r\n" +
// "文件类型:" + fileObj.type)
//}
'onQueueComplete'游耐: function (queueData) {
alert("文件上传成功!")
return
}
})
})
页面中的控件代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
<body>
<form id="form1" runat="server">
<div id="fileQueue">
</div>
<div>
<p>
<input type="file" name="uploadify" id="uploadify"/>
<input id="Button1" type="button" value="上传" onclick="javascript: $('#uploadify').uploadifyUpload()" />
<input id="Button2" type="button" value="取消" onclick="javascript:$('#uploadify').uploadifyClearQueue()" />
</p>
</div>
</form>
</body>
函数主要参数:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
$(document).ready(function() {
$('#fileInput1').fileUpload({
'uploader': 'uploader.swf',//不多讲了
'script': '/AjaxByJQuery/file.do',//处理Action
'cancelImg': 'cancel.png',
'folder': '',//服务端默认保存路径
'scriptData':{'methed':'uploadFile','arg1','value1'},
//向后台传递参数,methed,arg1为参数名,uploadFile,value1为对应的参数值,服务端通过request["arg1"]
'buttonText':'UpLoadFile',//按钮显示文字,不支持中文,解决方案见下
//'buttonImg':'图片路径',//通过设置背景图片解决中文问题,就是把背景图做成按钮的样子
'multi':'true',//多文件上传开关
'fileExt':'*.xls*.csv',//文件过滤器
'fileDesc':'.xls',//文件过滤器 详解见文档
'onComplete' : function(event,queueID,file,serverData,data){
//serverData为服务器端返回的字符串值
alert(serverData)
}
})
})
后台一般处理文件:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
using System
using System.Collections.Generic
using System.Linq
using System.IO
using System.Net
using System.Web
using System.Web.Services
namespace fupload
{
/// <summary>
/// Handler1 的摘要说明
/// </summary>
public class Handler1 : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain"
HttpPostedFile file = context.Request.Files["Filedata"]//对客户端文件的访问
string uploadPath = HttpContext.Current.Server.MapPath(@context.Request["folder"])+"\\"//服务器端文件保存路径
if (file != null)
{
if (!Directory.Exists(uploadPath))
{
Directory.CreateDirectory(uploadPath)//创建服务端文件夹
}
file.SaveAs(uploadPath + file.FileName)//保存文件
context.Response.Write("上传成功")
}
else
{
context.Response.Write("0")
}
}
public bool IsReusable
{
get
{
return false
}
}
}
}
以上方式基本可以实现多文件的上传,大文件大小是在控制在10M以下/。
1.Spring mvca.xml配置:
[html] view plain copy print?
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver" >
<!-- set the max upload size1MB 1048576 -->
<property name="maxUploadSize">
<value>52428800</value>
</property>
<散腊吵property name="maxInMemorySize">
<value>2048</value>
</property>
</bean>
b. 服务器端接收解析
[java] view plain copy print?
public void imgUpload(
MultipartHttpServletRequest multipartRequest,
HttpServletResponse response) throws Exception {
response.setContentType("text/htmlcharset=UTF-8")
Map<String, Object>局樱 result = new HashMap<String, Object>冲侍()
//获取多个file
for (Iterator it = multipartRequest.getFileNames()it.hasNext()) {
String key = (String) it.next()
MultipartFile imgFile = multipartRequest.getFile(key)
if (imgFile.getOriginalFilename().length() >0) {
String fileName = imgFile.getOriginalFilename()
//改成自己的对象哦!
Object obj = new Object()
//Constant.UPLOAD_GOODIMG_URL 是一个配置文件路径
try {
String uploadFileUrl = multipartRequest.getSession().getServletContext().getRealPath(Constant.UPLOAD_GOODIMG_URL)
File _apkFile = saveFileFromInputStream(imgFile.getInputStream(), uploadFileUrl, fileName)
if (_apkFile.exists()) {
FileInputStream fis = new FileInputStream(_apkFile)
} else
throw new FileNotFoundException("apk write failed:" + fileName)
List list = new ArrayList()
//将obj文件对象添加到list
list.add(obj)
result.put("success", true)
} catch (Exception e) {
result.put("success", false)
e.printStackTrace()
}
}
}
String json = new Gson().toJson(result,
new TypeToken<Map<String, Object>>() {
}.getType())
response.getWriter().print(json)
}
//保存文件
private File saveFileFromInputStream(InputStream stream, String path,
String filename) throws IOException {
File file = new File(path + "/" + filename)
FileOutputStream fs = new FileOutputStream(file)
byte[] buffer = new byte[1024 * 1024]
int bytesum = 0
int byteread = 0
while ((byteread = stream.read(buffer)) != -1) {
bytesum += byteread
fs.write(buffer, 0, byteread)
fs.flush()
}
fs.close()
stream.close()
return file
}
2.关于前端代码
a.修改ajaxfileupload.js
先到官网下载该插件.
将源文件的createUploadForm的代码替换如下:
[javascript] view plain copy print?
createUploadForm: function(id, fileElementId, data)
{
//create form
var formId = 'jUploadForm' + id
var fileId = 'jUploadFile' + id
var form = jQuery('<form action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>')
if (data) {
for ( var i in data) {
jQuery(
'<input type="hidden" name="' + i + '" value="'
+ data[i] + '" />').appendTo(form)
}
}
for (var i = 0i <fileElementId.lengthi ++) {
var oldElement = jQuery('#' + fileElementId[i])
var newElement = jQuery(oldElement).clone()
jQuery(oldElement).attr('id', fileElementId[i])
jQuery(oldElement).attr('name', fileElementId[i])
jQuery(oldElement).before(newElement)
jQuery(oldElement).appendTo(form)
}
//set attributes
jQuery(form).css('position', 'absolute')
jQuery(form).css('top', '-1200px')
jQuery(form).css('left', '-1200px')
jQuery(form).appendTo('body')
return form
}
第一步高定
b. 页面代码
html:
[html] view plain copy print?
<input type="button" value="添加附件" onclick="createInput('more')" />
<div id="more"></div>
js:这里可以专门写封装类,以及给file加onchange事件判断文件格式。由于时间有限,未修改
[javascript] view plain copy print?
var count = 1
/**
* 生成多附件上传框
*/
function createInput(parentId){
count++
var str = '<div name="div" ><font style="font-size:12px">附件</font>'+
' '+ '<input type="file" contentEditable="false" id="uploads' + count + '' +
'" name="uploads'+ count +'" value="" style="width: 220px"/><input type="button" value="删除" onclick="removeInput(event)" />'+'</div>'
document.getElementById(parentId).insertAdjacentHTML("beforeEnd",str)
}
/**
* 删除多附件删除框
*/
function removeInput(evt, parentId){
var el = evt.target == null ? evt.srcElement : evt.target
var div = el.parentNode
var cont = document.getElementById(parentId)
if(cont.removeChild(div) == null){
return false
}
return true
}
下面是2个修改多file用的js,用于显示和删除,可以于上面的合并精简代码:
[javascript] view plain copy print?
function addOldFile(data){
var str = '<div name="div' + data.name + '" ><a href="#" style="text-decoration:nonefont-size:12pxcolor:red" onclick="removeOldFile(event,' + data.id + ')">删除</a>'+
' ' + data.name +
'</div>'
document.getElementById('oldImg').innerHTML += str
}
function removeOldFile(evt, id){
//前端隐藏域,用来确定哪些file被删除,这里需要前端有个隐藏域
$("#imgIds").val($("#imgIds").val()=="" ? id :($("#imgIds").val() + "," + id))
var el = evt.target == null ? evt.srcElement : evt.target
var div = el.parentNode
var cont = document.getElementById('oldImg')
if(cont.removeChild(div) == null){
return false
}
return true
}
ajax上传文件:
[javascript] view plain copy print?
function ajaxFileUploadImg(id){
//获取file的全部id
var uplist = $("input[name^=uploads]")
var arrId = []
for (var i=0i<uplist.lengthi++){
if(uplist[i].value){
arrId[i] = uplist[i].id
}
}
$.ajaxFileUpload({
url:'xxxxx',
secureuri:false,
fileElementId: arrId, //这里不在是以前的id了,要写成数组的形式哦!
dataType: 'json',
data: {
//需要传输的数据
},
success: function (data){
},
error: function(data){
}
})
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)