ajax檔案上傳

來源:互聯網
上載者:User

標籤:hang   throws   bootstrap   ota   upload   repeat   ase   校正   source   

前台代碼:

 

<%@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檔案上傳

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.