Bootstrap-fileinput 多圖片上傳編輯
阿新 • • 發佈:2019-02-05
轉自:http://blog.csdn.net/wuwenjinwuwenjin/article/details/49507595
前言 :關於Bootstrap-fileinput 如何配置不做說明,自行去官網檢視。網址 : http://plugins.krajee.com/file-input
邏輯說明:先從後臺獲取資料展示,然後進行編輯。
廢話不多說, 直接上程式碼.
1. 頁面部分程式碼:
- <divclass="form-group">
- <labelfor="inputEmail3"class="col-xs-3 control-label">專案LOGO</label
- <divclass="col-xs-7">
- <inputid="testlogo"type="file"name="icoFile"class="file-loading"/>
- <inputtype="text"name="htestlogo"id="htestlogo"onchange="addFile(this)">
- </div>
- </div>
說明: 其中onchange()為我業務需要, 上傳完成後自動執行一個新增事件。 此方法可以去掉。
2. 獲取初始化資料方法:
- // 初始化獲取原有檔案
- $(function(){
- $.ajax({
- type : "post",
- url : "/eim/project/testFileUpload.do",
- dataType : "json",
- success : function(data) {
- layer.msg('操作成功!');
- showPhotos(data);
- },
- error: function(XMLHttpRequest, textStatus, errorThrown) {
- layer.msg('操作失敗!');
- }
- });
- });
3.初始化bootstrap-fileinput 元件:
- function showPhotos(djson){
- //後臺返回json字串轉換為json物件
- var reData = eval(djson);
- // 預覽圖片json資料組
- var preList = new Array();
- for ( var i = 0; i <reData.length; i++) {
- var array_element = reData[i];
- // 此處指標對.txt判斷,其餘自行新增
- if(array_element.fileIdFile.name.indexOf("txt")>0){
- // 非圖片型別的展示
- preList[i]= "<divclass='file-preview-other-frame'><divclass='file-preview-other'><spanclass='file-icon-4x'><iclass='fa fa-file-text-o text-info'></i></span></div></div>"
- }else{
- // 圖片型別
- preList[i]= "<imgsrc=\"/eim/upload/getIMG.do?savePath="+array_element.fileIdFile.filePath+"&name="+array_element.fileIdFile.name+"\" class=\"file-preview-image\">";
- }
- }
- var previewJson = preList;
- // 與上面 預覽圖片json資料組 對應的config資料
- var preConfigList = new Array();
- for ( var i = 0; i <reData.length; i++) {
- var array_element = reData[i];
- var tjson = {caption: array_element.fileIdFile.fileName, // 展示的檔名
- width: '120px',
- url: '/eim/project/deleteFile.do', // 刪除url
- key: array_element.id, // 刪除是Ajax向後臺傳遞的引數
- extra: {id: 100}
- };
- preConfigList[i] = tjson;
- }
- // 具體引數自行查詢
- $('#testlogo').fileinput({
- uploadUrl: '/eim/upload/uploadFile.do',
- uploadAsync:true,
- showCaption: true,
- showUpload: true,//是否顯示上傳按鈕
- showRemove: false,//是否顯示刪除按鈕
- showCaption: true,//是否顯示輸入框
- showPreview:true,
- showCancel:true,
- dropZoneEnabled: false,
- maxFileCount: 10,
- initialPreviewShowDelete:true,
- msgFilesTooMany: "選擇上傳的檔案數量 超過允許的最大數值!",
- initialPreview: previewJson,
- previewFileIcon: '<iclass="fa fa-file"></i>',
- allowedPreviewTypes: ['image'],
- previewFileIconSettings: {
- 'docx': '<iclass="fa fa-file-word-o text-primary"></i>',
- 'xlsx': '<iclass="fa fa-file-excel-o text-success"></i>',
- 'pptx': '<iclass="fa fa-file-powerpoint-o text-danger"></i>',
- 'pdf': '<iclass="fa fa-file-pdf-o text-danger"></i>',
- 'zip': '<iclass="fa fa-file-archive-o text-muted"></i>',
- 'sql': '<iclass="fa fa-file-word-o text-primary"></i>',
- },
- initialPreviewConfig: preConfigList
- }).off('filepreupload').on('filepreupload', function() {
- // alert(data.url);
- }).on("fileuploaded", function(event, outData) {
- //檔案上傳成功後返回的資料, 此處我只儲存返回檔案的id
- var result = outData.response.id;
- // 對應的input 賦值
- $('#htestlogo').val(result).change();
- });
- }
4. 後臺java儲存檔案部分程式碼
- @RequestMapping(value="/uploadFile",method=RequestMethod.POST)
- @ResponseBody
- public Object uploadFile(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- //轉型為MultipartHttpServletRequest
- MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest)request;
- //獲取檔案到map容器中
- Map<String,MultipartFile>fileMap = multipartRequest.getFileMap();
- //獲取頁面傳遞過來的路徑引數
- folderPath = request.getParameter("folder");
- String rootPath = BaseConfig.uploadPath;
- String filePath = rootPath + folderPath+"/";
- //檔案上傳並返回map容器,map儲存了檔案資訊
- FileModel fileModel = UploadifyUtils.uploadFiles(filePath,fileMap);
- boolean flag = service.add(fileModel);
- if(flag){
- String result = fileModel.getId()+";"+fileModel.getFilePath()+";"+fileModel.getName()+";"+fileModel.getFilePath();
- Map map = new HashMap<>();
- map.put("id", fileModel.getId());
- //返回檔案儲存ID
- //response.getWriter().write(map);
- return map;
- }
- return null;
- }
5.上傳完成後重新重新整理該元件即可。
最終展示效果 :
說明:此處指標對txt檔案型別判斷, 其餘的doc,ppt裡面有對應的展示圖示,只須在判斷是新增對應樣式即可
附:根據路徑過去/下載檔案程式碼:
- /**
- * 檔案下載
- *
- * @param savePath
- * 儲存目錄
- * @param name
- * 檔案原名
- * @param file
- * 儲存時的名稱 包含字尾
- * @param request
- * @param response
- * @return
- */
- public static String down(String savePath, String name, String fileName, HttpServletRequest request,
- HttpServletResponse response) {
- try {
- String path = savePath + "/" + name;
- File file = new File(path);
- if (!file.exists()) {
- // 不存在
- request.setAttribute("name", fileName);
- return "download_error";// 返回下載檔案不存在
- }
- response.setContentType("application/octet-stream");
- // 根據不同瀏覽器 設定response的Header
- String userAgent = request.getHeader("User-Agent").toLowerCase();
- if (userAgent.indexOf("msie") != -1) {
- // ie瀏覽器
- // System.out.println("ie瀏覽器");
- response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(name, "utf-8"));
- } else {
- response.addHeader("Content-Disposition",
- "attachment;filename=" + new String(name.getBytes("utf-8"), "ISO8859-1"));
- }
- response.addHeader("Content-Length", "" + file.length());
- // 以流的形式下載檔案
- InputStream fis = new BufferedInputStream(new FileInputStream(path));
- byte[] buffer = new byte[fis.available()];
- fis.read(buffer);
- fis.close();
- //response.setContentType("image/*"); // 設定返回的檔案型別
- OutputStream toClient = response.getOutputStream();
- OutputStream bos = new BufferedOutputStream(toClient);
- //BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(bos));
- bos.write(buffer);
- //bw.close();
- bos.close();
- toClient.close();
- return null;
- } catch (Exception e) {
- e.printStackTrace();
- //response.reset();
- return "exception";// 返回異常頁面
- } finally {
- /* if (toClient != null) {
- try {
- toClient.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }*/
- }
- }
附:
- UploadifyUtils.uploadFiles 部分程式碼
- public static FileModel uploadFiles(String savePath,Map<String,MultipartFile> fiLeMap){
- //上傳檔案
- //附件模型物件
- FileModel fm=new FileModel();
- try {
- File file = new File(savePath);
- //判斷資料夾是否存在,如果不存在則建立資料夾
- makeDir(file);
- if(fiLeMap!=null){
- for(Map.Entry<String, MultipartFile> entity:fiLeMap.entrySet()){
- MultipartFile f = entity.getValue();
- if(f!=null&&!f.isEmpty()){
- String uuid=UploadifyUtils.getUUID();//uuid作為儲存時的檔名
- String ext=UploadifyUtils.getFileExt(f.getOriginalFilename());//獲取檔案字尾
- //儲存檔案
- File newFile = new File(savePath+"/"+uuid+"."+ext);
- f.transferTo(newFile);
- fm.setFileName(f.getOriginalFilename());
- fm.setName(uuid+"."+ext);
- fm.setFilePath(savePath);//儲存路徑
- fm.setExt(ext);
- fm.setSize(f.getSize());
- }
- }
- }
- return fm;
- }catch (Exception e) {
- log.error(e);
- return null;
- }
- }
****************************************************************************************************************************************************************************
優化修改:
上面的檔案下載方法有一個bug。當上傳的檔名中存在特殊在字元( ,[] )時會導致無法下載。 可以改為使用spring下載代替流的方式。下面是程式碼:
- /**
- * @version 1.0
- * @Title: downLoad
- * @Description: spring下載附件
- * @param fileId 附件id
- * @param HttpServletRequest
- * @param HttpServletResponse
- * @author qcym
- * @date 2016年9月6日15:55:49
- * @throws
- */
- @RequestMapping(value="/downLoad")
- public ResponseEntity<byte[]> downLoad(String fileId,HttpServletRequest request,HttpServletResponse response){
- try {
- // 附件id不為空
- if(StringUtils.isNotEmpty(fileId)){
- // 獲取附件資訊
- MailFile mailFile = fileDao.selectByPrimaryKey(fileId);
- // 獲取附件真是名稱
- String fileName = mailFile.getFileRealname();
- // 獲取伺服器上的檔案
- String filePath = mailFile.getFileUrl()+mailFile.getFileName();
- File file = new File(filePath);
- HttpHeaders headers = new HttpHeaders();
- fileName=new String(fileName.getBytes("UTF-8"),"iso-8859-1");//為了解決中文名稱亂碼問題
- headers.setContentDispositionFormData("attachment", fileName);
- headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
- return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
- headers, HttpStatus.CREATED);
- }
- }catch (Exception e) {
- e.printStackTrace();
- throw new BusinessException("1014", "附件下載錯誤:"+e.getMessage());
- }
- return null;
- }