ajax文件上传
Posted 贪吃的柳柳
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ajax文件上传相关的知识,希望对你有一定的参考价值。
前台代码:
<%@page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<link rel="stylesheet" type="text/css" href="assets/plugins/bootstrap-fileupload/bootstrap-fileupload.css" />
<script type="text/javascript" src="assets/plugins/bootstrap-fileupload/bootstrap-fileupload.js"></script>
<script type="text/javascript" src="assets/plugins/jquery.pulsate.min.js"></script>
<script type="text/javascript" src="assets/plugins/ajaxfileupload.js"></script>
<!-- begin page level javascript -->
<!-- end page level javascript -->
<!-- begin begin page level form -->
<div class="row" id="wholeDiv">
<div class="col-md-12">
<div class="col-md-9">
<div class="fileupload fileupload-new" data-provides="fileupload">
<div class="input-group">
<span class="input-group-btn">
<span class="uneditable-input">
<i class="fa fa-file fileupload-exists"></i>
<span class="fileupload-preview"></span>
</span>
</span>
<span class="btn default btn-file">
<span class="fileupload-new"><i class="fa fa-paper-clip"></i> 选择导入文件</span>
<span class="fileupload-exists"><i class="fa fa-undo"></i> 修改</span>
<input type="file" class="default" name="file" id="excelFile"/>
</span>
<a href="#" class="btn red fileupload-exists" data-dismiss="fileupload"><i class="fa fa-trash-o"></i> 清除</a>
</div>
</div>
<span class="label label-danger">注意</span>
<span>请上传xls或xlsx文件</span>
</div>
<div class="col-md-9">
<div class="fileupload fileupload-new" data-provides="fileupload">
<div class="input-group">
<span class="input-group-btn">
<span class="uneditable-input">
<i class="fa fa-file fileupload-exists"></i>
<span class="fileupload-preview"></span>
</span>
</span>
<span class="btn default btn-file">
<span class="fileupload-new"><i class="fa fa-paper-clip"></i> 选择导入文件</span>
<span class="fileupload-exists"><i class="fa fa-undo"></i> 修改</span>
<input type="file" class="default" name="file" id="excelFile"/>
</span>
<a href="#" class="btn red fileupload-exists" data-dismiss="fileupload"><i class="fa fa-trash-o"></i> 清除</a>
</div>
</div>
<span class="label label-danger">注意</span>
<span>请上传xls或xlsx文件</span>
</div>
<div class="form-group">
<div class=‘col-md-offset-3 col-md-8‘>
<button type="button" id="modalBatchAddBtn" class="btn blue start"><i class="fa fa-upload"></i> 确认</button>
<button type="button" id="modalBatchReturnBtn" class="btn blue start"><i class="fa fa-reply"></i> 返回</button>
</div>
</div>
</div>
<div id="importResult">
</div>
</div>
<!-- end begin page level form -->
<script >
$(document).ready(function(){
$(‘#modalBatchAddBtn‘).on(‘click‘, function(){
// 手动校验 会弄乱样式,改成不选择文件则点击每反应
/* if(!$(‘#excelFile‘).val()){
$(‘#objBatchAddForm .uneditable-input‘).pulsate({
color: "#ff0000",
repeat: false
});
return false;
}
var fileExt = (/[.]/.exec($(‘#excelFile‘).val())) ? /[^.]+$/.exec($(‘#excelFile‘).val().toLowerCase()) : ‘‘;
if(fileExt != ‘xls‘ && fileExt != ‘xlsx‘)
{
$(‘#objBatchAddForm .uneditable-input‘).pulsate({
color: "#ff0000",
repeat: false
});
return false;
}
*/
var formData = new FormData();
formData.append("uploadAddFileInput",$("#excelFile")[0].files[0]);
console.log($("#excelFile")[0]);
console.log($("#excelFile")[1]);
formData.append("uploadAddFileInput1",$("#excelFile")[1].files[0]);
$.ajax({
url : ‘${pageContext.request.contextPath}/console/testRes/shangchuan‘,
type : ‘POST‘,
data : formData,
// 告诉jQuery不要去处理发送的数据
processData : false,
// 告诉jQuery不要去设置Content-Type请求头
contentType : false,
beforeSend:function(){
console.log("正在进行,请稍候");
},
success : function(responseStr) {
if(responseStr.status===0){
console.log("成功"+responseStr);
}else{
console.log("失败");
}
},
error : function(responseStr) {
console.log("error");
}
});
/* Custom.ajaxSubmit({
url : ‘${pageContext.request.contextPath}/console/pcProjectImport/upload‘,
formId : ‘objBatchAddForm‘,
dataType : "html",
success : function(data){
},
blockel : ‘.page-content‘
}); */
$(‘#static‘).modal(‘hide‘);
});
$("#modalBatchReturnBtn").on(‘click‘,function(){
Custom.easyLoad(‘${pageContext.request.contextPath}/console/pcProjectImport/index‘);
})
});
</script>
后台---------------------------------》
public void shangchuan(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("text/plain; charset=UTF-8");
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
MultipartFile myfile = multipartRequest.getFile("uploadAddFileInput");
String originalFilename = myfile.getOriginalFilename();
System.out.println("文件原名: " + originalFilename);
System.out.println("文件名称: " + myfile.getName());
System.out.println("文件长度: " + myfile.getSize());
System.out.println("文件类型: " + myfile.getContentType());
/*String path = request.getSession().getServletContext().getRealPath("resources/importExcel") + "/"
+ originalFilename*/;
String path="E:/upload/"+originalFilename;
SaveFileFromInputStream(myfile.getInputStream(), path);// 保存到服务器的路径
}
public void SaveFileFromInputStream(InputStream stream, String path) throws IOException {
File path1 = new File(path);
if(!path1.exists()){
File file = new File(path);
}
FileOutputStream fs = new FileOutputStream(path1);
System.out.println("------------" + path1);
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();
}
-------------------------------------------------------------
--------------------------------------------------------------
如果是excel,需要将数据读入数据库的话,后台如下
public String upload(DrlsRequest request, MultipartFile file, ModelMap map) throws IOException {
InputStream in=file.getInputStream();
// // 得到工作表
Workbook book = WorkbookFactory.create(in);
// // 得到第一页
Sheet sheet = book.getSheetAt(0);
// // 得到第一面的所有行
Iterator<Row> row = sheet.rowIterator();
// 得到第一行,也就是标题行
Row title = row.next();
// 得到第一行的所有列
Iterator<Cell> cellTitle = title.cellIterator();
// 将标题的文字内容放入到一个map中。
Map<Integer, String> titlemap = new HashMap<Integer, String>();
List<String> cellNameList = new ArrayList<>();
// 从标题第一列开始
int i = 0;
// 循环标题所有的列
while (cellTitle.hasNext()) {
Cell cell = cellTitle.next();
String value = (cell.getStringCellValue() == null ? cell.getStringCellValue()
: cell.getStringCellValue().trim());
titlemap.put(i, value);
cellNameList.add(value);
i = i + 1;
}
while (row.hasNext()) {
// 标题下的第一行
Row rown = row.next();
// 行的所有列
Iterator<Cell> cellbody = rown.cellIterator();
// 得到传入类的实例
T tObject = pojoClass.newInstance();
int k = 0;
// 遍历一行的列
while (cellbody.hasNext()) {
Cell cell = cellbody.next();
// 这里得到此列的对应的标题
String titleString = (String) titlemap.get(k);
// 如果这一列的标题和类中的某一列的Annotation相同,那么则调用此类的的set方法,进行设值
if (fieldSetMap.containsKey(titleString)) {
Method setMethod = (Method) fieldSetMap.get(titleString);
// 得到setter方法的参数
Type[] ts = setMethod.getGenericParameterTypes();
// 只要一个参数
String xclass = ts[0].toString();
if (fieldSetConvertMap.containsKey(titleString)) {
fieldSetConvertMap.get(titleString).invoke(tObject, cell.getStringCellValue());
} else {
invokeByType(tObject, cell, setMethod, xclass);
}
}
// 下一列
k = k + 1;
}
dist.add(tObject);
}
}
以上是关于ajax文件上传的主要内容,如果未能解决你的问题,请参考以下文章