您的位置:首页 > 其它

SSM 上传多个文件也可以上传多张图片

2019-01-03 14:42 190 查看

SSM 可上传多个文件使用form表单的异步提交,可做参考哟

 html 代码块:

[code]<form class="layui-form" id="formreset" enctype="multipart/form-data">
<div class="layui-form-item">
<button type="button" id="updateDrug" class="layui-btn"
onclick="addFile()">多文件上传</button>
<button class="layui-btn" lay-submit="" lay-filter="formDemo">立即提交</button>
<div class="layui-form-item">
<input type="file" id="attachment" class="hidden"
onchange="upAttachment()" hidden />
<div id="container" class="container"
style="padding-top: 5px;width:84%;display:none;margin-left:55px;">
<table>
<thead>
<tr>
<th style="width:10%;">序号</th>
<th style="width:30%;">文件名</th>
<th style="width:30%;">图片</th>
<th style="width:10%;">大小</th>
<th style="width:10%;">类型</th>
<th style="width:10%;">移除</th>
</tr>
</thead>
<tbody>

</tbody>
</table>
</div>
</div>
</div>
</form>

 

JS代码

[code]function addFile() {
$('#container').show();
var html = '<tr>';
html += '<td><input type="file" name="pictures" id="idpictures" style="display:none;" onchange="processFiles(this,this.files)">' + ($('#container tbody tr').length + 1) + '</td>';
html += '<td></td>';
html += '<td><img src="" style="width: 150px;margin: 0px auto;display: block;" class="tdImg" /></td>';
html += '<td></td>';
html += '<td></td>';
html += '<td><input type="button" value="移除" onclick="delFile(this)" class="layui-btn layui-btn-danger"></td>';
html += '</tr>';

$('#container table tbody').append(html);
$('#container table tbody tr:last-child td:first-child>input').click();

}

// 选择文件
function processFiles(t, files) {
if (files == null || files.length <= 0) {
delFile(t); // 移除
}

var file = files[0];
var name = file.name; // 名称
var img = file.webkitRelativePath;//路径
var size = change(file.size); // 大小
var type = file.type; // 类型
var arr = $(t).parent('td').parent('tr').find('td');

if (arr.length >= 1) $(arr[1]).html(name);
if (arr.length >= 2) {
$(arr[2]).find('img').attr('src', window.URL.createObjectURL(file));//显示图片在表格里
}
if (arr.length >= 3) $(arr[3]).html(size);
if (arr.length >= 4) $(arr[4]).html(type);
}

//移除不需要的图片
function delFile(t) {
$(t).parent('td').parent('tr').remove();
}

// js中字节B转化成KB,MB,GB
function change(limit) {
var size = "";
if (limit < 0.1 * 1024) { // 小于0.1KB,则转化成B
size = limit.toFixed(2) + "B"
} else if (limit < 0.1 * 1024 * 1024) { // 小于0.1MB,则转化成KB
size = (limit / 1024).toFixed(2) + "KB"
} else if (limit < 0.1 * 1024 * 1024 * 1024) { // 小于0.1GB,则转化成MB
size = (limit / (1024 * 1024)).toFixed(2) + "MB"
} else { // 其他转化成GB
size = (limit / (1024 * 1024 * 1024)).toFixed(2) + "GB"
}

var sizeStr = size + ""; // 转成字符串
var index = sizeStr.indexOf("."); // 获取小数点处的索引
var dou = sizeStr.substr(index + 1, 2) // 获取小数点后两位的值
if (dou == "00") { // 判断后两位是否为00,如果是则删除00
return sizeStr.substring(0, index) + sizeStr.substr(index + 3, 2)
}
return size;
}

 

ajaxSubmit()提交表单,使用第三方插件jquery.form实现;

[code]         // 显示加载页面
var loadIndex = layer.load(0, {
shade: 0.3
}); // 0代表加载的风格,支持0-2
//整个表单提交
$("#formreset").ajaxSubmit({
type: 'POST',
// 可选get
url: ctx + "/drug/insertdrug.do",
// 这里是接收数据的PHP程序
data: {
type: type
},
// 传给PHP的数据,多个参数用&连接
dataType: 'json',
// 服务器返回的数据类型 可选XML ,Json jsonp script html text等
scriptCharset: 'UTF-8',
success: function(data, textStatus) {
layer.close(loadIndex);
if (data.state == 'ok') {
layer.msg(data.msg);
selectData(); // 刷新查询
} else {
layer.msg(data.msg);
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
layer.close(loadIndex);
layer.msg('保存失败:' + errorThrown);
}
});

后台代码:

[code]/**
* 新增
*
* @param type
* @param data   表单提交过来保存其他的字段
* @param file  上传文件获取的数据
* @param request
* @return
*/
//pictures 要跟name值对应
@RequestMapping(value = "/insertdrug", produces = { "application/json;charset=UTF-8" })
@ResponseBody
public String insert(String type,Drugdata data,
@RequestParam(value = "pictures", required = false) MultipartFile[] file,
HttpServletRequest request) {
JSONObject json = new JSONObject();
json.put("msg", "");
json.put("state", "no");
String msg = "";
String state = "no";
boolean isdelete = false;
data.setIsdelete(isdelete);
try {
String ss = "";
String path = "";
for (MultipartFile mf : file) {
System.out.println(file.length);
if (!mf.isEmpty()) {
// 使用UUID给图片重命名,并去掉四个“-”
String name = UUID.randomUUID().toString()
.replaceAll("-", "");
// 获取文件的扩展名
String ext = FilenameUtils.getExtension(mf
.getOriginalFilename());
// 设置图片上传路径
String url = request.getSession().getServletContext()
.getRealPath("/upload");
System.out.println(url);
// 以绝对路径保存重名命后的图片
mf.transferTo(new File(url + "/" + name + "." + ext));
// 把图片存储路径保存到数据库
path = "upload/" + name + "." + ext;
}
ss = ss + path + ","; 	//我这里是一个字段保存多张图片,所以要拼接起来 ','分隔符
System.out.println(ss);
}

ss = ss.substring(0, ss.length() - 1);// 截取后面多余的一个分隔符
data.setPicture(ss);
int intR = drugdataService.insert(data);
if (intR > 0) {
state = "ok";
msg = "新增成功";
} else {
state = "no";
msg = "新增失败";
}

} catch (Exception e) {
msg = e.getMessage();
}
json.put("msg", msg);
json.put("state", state);
return json.toString();
}

就这样就可以上传成功了^.^,不会的可以参考一下

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐