ajaxfileupload+springmvc上传多文件的control怎么写

 我来答
就烦条0o
2016-05-15 · 知道合伙人软件行家
就烦条0o
知道合伙人软件行家
采纳数:33315 获赞数:46493
从事多年系统运维,喜欢编写各种小程序和脚本。

向TA提问 私信TA
展开全部
1.Spring mvc

a.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/html;charset=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 = 0; i < fileElementId.length; i ++) {
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:none;font-size:12px;color: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=0; i< uplist.length; i++){
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){
}
});
}
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式