ExtJS 3.4.0 - Upload Multiple Files

由於一般上傳的按鈕在跳出視窗選擇檔案時只能拉取一檔案做上傳,而在這邊要探討的是如

何利用ExtJS搭配HTML5語法及相關的後端程式來做處理,達到可以一次選取多個檔案做上

傳的目的。

首先一樣先載入相關的JS Library

ext-all.js
adapter/ext/ext-base.js
resources/css/ext-all.css

HTML部分
  1. <form id="myform" name="myform" method="post" enctype="multipart/form-data">
  2. <div id="content"></div>
  3. </form>

建立一div區塊,到時會定義一ExtJS Container與它做綁定

ExtJS部分
  1. Ext.onReady(function(){
  2. Ext.QuickTips.init();
  3. var container = new Ext.Container({
  4. width: 300,
  5. layout: 'column',
  6. items:[
  7. {
  8. xtype: 'textfield',
  9. inputType: 'file',
  10. fieldLabel: 'Multiple file selection',
  11. autoCreate: {
  12. tag: 'input',
  13. type: 'text',
  14. size: '20',
  15. autocomplete: 'off',
  16. multiple: 'multiple'
  17. }
  18. },
  19. {
  20. xtype: 'button',
  21. text:'確認',
  22. id:'doForm',
  23. listeners: {
  24. click: function() {
  25. Ext.Ajax.request({
  26. url: 'more-files-upload.jsp',
  27. form: myform,
  28. method: 'POST',
  29. success: function ( result, request) {
  30. var json_t = Ext.util.JSON.decode(result.responseText);
  31. Ext.Msg.alert('Success', json_t.info);
  32. },
  33. failure: function ( result, request) {
  34. Ext.Msg.show({
  35. title : '訊息',
  36. msg : '上傳失敗!!',
  37. buttons: Ext.Msg.OK,
  38. closable:false,
  39. icon : Ext.Msg.ERROR
  40. });
  41. }
  42. });
  43. }
  44. }
  45. }
  46. ],
  47. style: 'margin:20px'
  48. });
  49. container.render('content');
  50. });

Container內另外定義一textfield其type為file及一button,並且針對file多加一屬性multiple。

而multiple屬性以IE來講需要10才有支援,屬於HTML5新加的屬性

http://www.w3schools.com/tags/att_input_multiple.asp

JSP部分

與之前這篇文章一樣,後端改寫一下需針對實際的檔案數目來做各別save的動作,搭配

smartupload library省事很多!

  1. try{
  2. response.setHeader("Cache-Control", "no-cache");
  3. SmartUpload su = new SmartUpload();
  4. su.initialize(pageContext);
  5. su.setAllowedFilesList("txt");
  6. su.upload();
  7. for(int i = 0 ; i < su.getFiles().getCount() ; i++){
  8. com.jspsmart.upload.File file = su.getFiles().getFile(i);
  9. System.out.println(">>>>>>file name:" + file.getFileName());
  10. file.saveAs("uploadFileTest_"+i+".txt", su.SAVE_PHYSICAL);
  11. }
  12. JSONObject json = new JSONObject();
  13. json.put("success", true);
  14. json.put("info", "upload success!");
  15. response.getWriter().print(json.toString());
  16. response.getWriter().flush();
  17. }catch(Exception e){
  18. e.printStackTrace();
  19. response.getWriter().print(e.getMessage());
  20. }finally {
  21. try {
  22. response.getWriter().close();
  23. } catch (IOException e) {
  24. e.printStackTrace();
  25. }
  26. }

DEMO


留言