bootstrap上傳按鈕
㈠ bootstrap fileinput 上傳失敗,求助
最近因為項目需要研究了下bootstrap fileinput的使用,來記錄下這幾天的使用心得吧。
前台html頁面的代碼
<form role="form" id="importFile" method="post"並鬧
enctype="multipart/form-data">
<div class="row">
<div class="col-md-3" >
</div>
<div class="col-md-3 ">
<input type="radio" name="excelType" class="radio" id="line" value="line"><label for="line"> 參數2</label>
</div>
<div class="col-md-3 ">
<input type="radio" name="excelType" class="radio" id="pipeline" value="pipeline"><label for="pipeline"> 參數3</label>
</div>
<div class="col-md-3 ">
<input type="radio" name="excelType" class="radio" id="jdj" value="jdj"><label for="jdj"> 參數4</label>
</div>
</div>
<input id="excelFile" name="excelFile" class="file-loading"
type="file" multiple accept=".xls,.xlsx" data-min-file-count="1"
data-show-preview="true"> <br>
</form>
js進行插件的初始化和一些參數的設置
$("#excelFile").fileinput({
uploadUrl:"rest/import/importExcel",//上傳的地址
uploadAsync: true,
language : "zh",//設置語言
showCaption: true,//是否顯示標題
showUpload: true, //是否顯示上傳按鈕
browseClass: "btn btn-primary", //按鈕樣絕遲罩式
allowedFileExtensions: ["xls", "xlsx"], //接收的文件後綴
maxFileCount: 10,//最大上傳文件數限制
uploadAsync: true,
previewFileIcon: '<i class="glyphicon glyphicon-file"></i>',
allowedPreviewTypes: null,
previewFileIconSettings: {
'docx': '<i class="glyphicon glyphicon-file"></i>',
'xlsx': '<i class="glyphicon glyphicon-file"></i>',
'pptx': '<i class="glyphicon glyphicon-file"></i>',
旦含'jpg': '<i class="glyphicon glyphicon-picture"></i>',
'pdf': '<i class="glyphicon glyphicon-file"></i>',
'zip': '<i class="glyphicon glyphicon-file"></i>',
},
uploadExtraData: function() {
var extraValue = null;
var radios = document.getElementsByName('excelType');
for(var i=0;i<radios.length;i++){
if(radios[i].checked){
extraValue = radios[i].value;
}
}
return {"excelType": extraValue};
}
});
注意: uploadExtraData函數中只能用原生JS來取值,不能用JQuery來獲取值,此參數用來向後台傳遞附加參數,以方便處理,最簡單的寫法是:
uploadExtraData: {
"excelType": document.getElementByID('id')
}
<input type="radio" name="excelType" class="radio網路搜索引擎營銷sem競價培訓班http://www.yingtaow.com/pxfw?id="station" value="station"><label for="station"> 參數1</label>
文件上傳成功後的回調方法
$("#excelFile").on("fileuploaded", function(event, data, previewId, index) {
alert("上傳成功!");
$("#excelImport").modal("hide");
//後台處理後返回的經緯度坐標json數組,
var array = data.response;
console.dir(array);
//jquery循環取經緯度坐標
$.each(array,function(index,latAndLon){
var lon = latAndLon.lon;
var lat = latAndLon.lat;
var point = new Point(lon, lat, map.spatialReference);
var symbol = new esri.symbol.SimpleMarkerSymbol().setStyle(
SimpleMarkerSymbol.STYLE_CIRCLE).setColor(
new Color([255,255,0,0.5]));
var attr = {"address": "addressName" };
var infoTemplate = new esri.InfoTemplate("標題", "地址 :${address}");
var graphic = new Graphic(point,symbol,attr,infoTemplate);
map.graphics.add(graphic);
});
});
arcgis中點的定義的兩種方法:
var point = new Point(lon, lat, new SpatialReference({ wkid: 4326 }));
var point = new Point(lon, lat, map.spatialReference);
後台Java處理,使用common fileupload插件來實現,此處限制只能上傳excel 文件
public JSONArray importExcel(HttpServletRequest request,
HttpServletResponse response) throws Exception {
final String allowFileSuffix = "xls,xlsx";
Subject subject = SecurityUtils.getSubject();
String uname = (String) subject.getPrincipal();
String basePath = "D:" + File.separator + uname;
File tmpDir = new File(basePath);// 初始化上傳文件的臨時存放目錄
JSONArray jsonArry = new JSONArray();
if (!tmpDir.exists()) {
tmpDir.mkdirs();
}
// 檢查輸入請求是否為multipart表單數據。
if (ServletFileUpload.isMultipartContent(request)) {
DiskFileItemFactory dff = new DiskFileItemFactory();// 創建該對象
dff.setRepository(tmpDir);// 指定上傳文件的臨時目錄
dff.setSizeThreshold(1024000);// 指定在內存中緩存數據大小,單位為byte
ServletFileUpload sfu = new ServletFileUpload(dff);// 創建該對象
// sfu.setFileSizeMax(5000000);//指定單個上傳文件的最大尺寸
sfu.setSizeMax(10000000);// 指定一次上傳多個文件的總尺寸
sfu.setHeaderEncoding("utf-8");
String type = null;
List<FileItem> fileItems = new ArrayList<FileItem>();
try {
fileItems = sfu.parseRequest(request);
} catch (FileUploadException e1) {
System.out.println("文件上傳發生錯誤" + e1.getMessage());
}
String fullPath = null;
String fileName = null;
for (FileItem fileItem : fileItems) {
// 判斷該表單項是否是普通類型
if (fileItem.isFormField()) {
String name = fileItem.getFieldName();// 控制項名
String value = fileItem.getString();
if (name.equals("excelType")) {
type = value;
}
} else {
String filePath = fileItem.getName();
if (filePath == null || filePath.trim().length() == 0)
continue;
fileName = filePath.substring(filePath
.lastIndexOf(File.separator) + 1);
String extName = filePath.substring(filePath
.lastIndexOf(".") + 1);
fullPath = basePath + File.separator + fileName;
if (allowFileSuffix.indexOf(extName) != -1) {
try {
fileItem.write(new File(fullPath));
} catch (Exception e) {
e.printStackTrace();
}
} else {
throw new FileUploadException("文件格式不正確");
}
}
}
if (type.equals("station")) {
jsonArry = readExcel(fullPath, fileName);
} else if (type.equals("line")) {
System.out.println("===============:line");
} else if (type.equals("pipeline")) {
System.out.println("===============:pipeline");
} else if (type.equals("jdj")) {
System.out.println("===============:jdj");
}
}
return jsonArry;
}
// 判斷文件類型
public Workbook createWorkBook(InputStream is, String excelFileName)
throws IOException {
if (excelFileName.toLowerCase().endsWith("xls")) {
return new HSSFWorkbook(is);
}
if (excelFileName.toLowerCase().endsWith("xlsx")) {
return new XSSFWorkbook(is);
}
return null;
}
public JSONArray readExcel(String basePath, String fileName)
throws FileNotFoundException, IOException {
File file = new File(basePath);
Workbook book = createWorkBook(new FileInputStream(file), fileName);
JSONObject jsonObj = new JSONObject();
JSONArray jsonArry = new JSONArray();
Sheet sheet = book.getSheetAt(0);
for (int i = 3; i < sheet.getLastRowNum(); i++) {
Row row = sheet.getRow(i);
String lon = row.getCell(2).getNumericCellValue() + "";
String lat = row.getCell(3).getNumericCellValue() + "";
jsonObj.put("lat", lat);// 緯度
jsonObj.put("lon", lon);// 經度
jsonArry.add(jsonObj);
}
System.out.println(jsonArry.toString());
return jsonArry;
}
㈡ bootstrap-fileinput組件怎麼在上傳時指定額外的URL參數
由於英文水平問題,閱讀官方文檔時沒有找到該問題的解決方法,於是去github提了一個issue ,得到的答案是仔細閱讀文檔,裡面有一個回調函數可以解決問題??
解決方法
關鍵的配置參數是uploadExtraData
具體的代碼如下:
//獲得額外參數的方法
fodderType = function() {
return $("#fodderTypeSelect").val();
};
//初始化fileinput控制項(第一次初始化)
function initFileInput(ctrlName, FileExtensions, fileSize) {
var control = $('#' + ctrlName);
control.fileinput({
language: 'zh', //設置語言
uploadUrl: "/WxMedia/ImageUpload", //上傳的地址
allowedFileExtensions: FileExtensions, //接收的文件後綴
showUpload: true, //是否顯示上傳按鈕
showCaption: true, //是否顯示標題,
maxFileSize: fileSize * 1000, //單位為kb,如果為0表示不限制文件大小
browseClass: "btn btn-primary", //按鈕樣式
previewFileIcon: "<i class='glyphicon glyphicon-king'></i>",
initialCaption: "請選擇上傳素材",
uploadExtraData: function(previewId, index) { //額外參數的關鍵點
var obj = {};
obj.fodder = fodderType();
console.log(obj);
return obj;
}
});
}
關鍵點:
可以看到配置文件中uploadExtraData的參數是一個函數形式,這是一個回調函數,會在上傳時調用,讀取配置的額外參數。