来自 前端技术 2019-09-04 19:43 的文章
当前位置: 六合联盟网 > 前端技术 > 正文

实现文件上传和下载,文件上传

效果要求:

率先下载四个包 commons-fileupload-?.jar和commons-io-?.jar  将他们配备到你的项目中

在mastplan页面增添按键,实现上传excel文件的功用,并在保留此前读取文件内容将其保存到数据Curry面。

先把它们位于 "项目名/war/WEB-INF/lib" 中,之后直接在 properties 中出席到品种中(没安排过能够去互连网查eclipse配置jar的不二法门,不会细小略的)

 

 

实际落实:

从此以往就起来啦,client 端代码:

 

 

^_^ 先闪闪图片吧。

[java] view plaincopyprint?

 图片 1  

  1. final FileUpload fileUpload = new FileUpload();  
  2. final FormPanel formpanel = new FormPanel();  
  3.   
  4. fileUpload.setName("uploadFormElement");  
  5.         formpanel.setEncoding( FormPanel.ENCODING_MULTIPART );  
  6.         formpanel.setMethod( FormPanel.METHOD_POST );  
  7.         formpanel.setAction( GWT.getModuleBaseURL() + "fileupload" );  
  8.         formpanel.setWidget( fileUpload );  
  9.           
  10.         uploadbutton.addClickHandler( new ClickHandler() {  
  11.             public void onClick( ClickEvent sender ) {  
  12.                 formpanel.submit();  
  13.             }  
  14.         });  
  15.         formpanel.addSubmitHandler( new SubmitHandler() {  
  16.             public void onSubmit(SubmitEvent event) {  
  17.                 if( fileUpload.getFilename().length() == 0 ) {  
  18.                     Window.alert( "you must select a file" );  
  19.                 }  
  20.                   
  21.             }  
  22.         });  
  23.         formpanel.addSubmitCompleteHandler( new SubmitCompleteHandler() {  
  24.             public void onSubmitComplete(SubmitCompleteEvent event) {  
  25.                 //包容linux文件分隔符?  
  26.                 String selected = fileUpload.getFilename().replaceAll("/", "//");  
  27.                 selected = selected.substring( selected.lastIndexOf("//")+1);  
  28.                                 Window.alert( "upload complete"+ event.getResults());  
  29.             }  
  30.         });  

 

final FileUpload fileUpload = new FileUpload(); final FormPanel formpanel = new FormPanel(); fileUpload.setName("uploadFormElement"); formpanel.setEncoding( FormPanel.ENCODING_MULTIPART ); formpanel.setMethod( FormPanel.METHOD_POST ); formpanel.setAction( GWT.getModuleBaseU君越L() + "fileupload" ); formpanel.setWidget( fileUpload ); uploadbutton.addClickHandler( new ClickHandler() { public void onClick( ClickEvent sender ) { formpanel.submit(); } }); formpanel.addSubmitHandler( new SubmitHandler() { public void onSubmit(Submit伊夫nt event) { if( fileUpload.getFilename().length() == 0 ) { Window.alert( "you must select a file" ); } } }); formpanel.addSubmitCompleteHandler( new SubmitCompleteHandler() { public void onSubmitComplete(SubmitCompleteEvent event) { //包容linux文件分隔符? String selected = fileUpload.getFilename().replaceAll("/", "//"); selected = selected.substring( selected.lastIndexOf("//")+1); Window.alert( "upload complete"+ event.getResults()); } });

 图片 2  

 

Jsp页面代码:

以后再server中增多服务 :FileUploadServlet.java

在tbar工具栏中增加一开关: 单击此开关,弹出贰个上传文件的窗口

 

 

[java] view plaincopyprint?

[java] 
,{id:"upload_excel",xtype: "button",cls:"x-btn-icon",icon:"/_static/icon/upload_excel.png",tooltip:"upload",scope:this,handler: function(){win_upload.show();}} 
 
 
var win_upload = new Ext.Window({ 
    title : 'UploadFile', 
    width :450, 
    height : 180, 
    modal : true, 
    x : 100, 
    y : 50, 
    layout : 'form', 
    autoScroll : true, 
    constrain : true, 
    bodyStyle : 'padding:10px 10px 10px 10px;', 
    items:form, 
    buttons : [{ 
        text : '確認上傳', 
      handler : function() { 
       if (form.form.isValid()) { 
        if(Ext.getCmp('userfile').getValue() == ''){ 
         Ext.Msg.alert('溫馨提醒','請選擇要上傳的文书'); 
         return; 
        } 
        Ext.MessageBox.show({ 
           title : '請稍後....', 
           msg : '文件正在上傳中....', 
           progressText : '', 
           width : 300, 
           progress : true, 
           closable : false, 
           animEl : 'loding' 
        }); 
        form.getForm().submit({ 
            url : 'upload', 
            method : 'POST', 
            success : function(form, action) { 
            Ext.Msg.alert('成功','恭喜!文件上傳成功!'+action.result.success); 
            win_upload.hide(); 
         }, 
         failure : function(form, action) { 
            Ext.Msg.alert('錯誤',"文件上傳失敗,請重新操作!"); 
         } 
        }) 
       } 
      } 
    }, { 
        text : 'Close', 
        handler : function() { 
            win_upload.hide(); 
    } 
    }], 
    closable: false, 
    draggable: false, 
    resizable: false 
}); 
 
 
Java代码: 
在保存文件从前获得流消息,并将其读出。 
获取excel内容 
 
package javaservlets.production.uploadexcel; 
 
import java.io.IOException; 
import java.io.InputStream; 
import java.util.List; 
 
import javax.servlet.ServletException; 
import javax.servlet.http.HttpServlet; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 
 
import jxl.Cell; 
import jxl.Sheet; 
import jxl.Workbook; 
import jxl.read.biff.BiffException; 
 
import org.apache.commons.fileupload.FileItem; 
import org.apache.commons.fileupload.FileUploadException; 
import org.apache.commons.fileupload.disk.DiskFileItemFactory; 
import org.apache.commons.fileupload.servlet.ServletFileUpload; 
import org.json.JSONException; 
import org.json.JSONObject; 
 
public class Upload extends HttpServlet { 
 
    private static final long serialVersionUID = 6777945010008132796L; 
 
    @Override 
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 
        super.doGet(req, resp); 
        System.out.println("doGet"); 
        resp.sendRedirect("/upload/index.jsp"); 
    } 
     
    @Override 
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) { 
         
System.out.println("--------------------------------- upload ---------------------------------------------------"); 
         
        InputStream is = null; 
        Workbook workbook = null; 
         
        try { 
            List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(req); 
            for (FileItem item : items) { 
                if (item.isFormField()) { 
                    System.out.println(item.getFieldName()); 
                    System.out.println(item.getString()); 
                } else { 
                    System.out.println(item.getFieldName()); 
                    is = item.getInputStream(); 
                    workbook = Workbook.getWorkbook(is); 
                } 
            } 
     
       Sheet[] sheetNum = workbook.getSheets(); 
System.out.println("----------------------------------打印sheet的個數:"+sheetNum.length+"----------------------------"); 
       Sheet sheet = workbook.getSheet(0); 
       Cell cell = null; 
 
       int columnCount = sheet.getColumns(); 
       int rowCount = sheet.getRows(); 
       for (int i = 0; i < rowCount; i++) { 
           for (int j = 0; j < columnCount; j++) { 
              cell = sheet.getCell(j, i); 
              System.out.print(cell.getContents()); 
           } 
           System.out.println(" n"); 
       } 
           resp.setContentType("text/html"); 
           JSONObject jObject = new JSONObject(); 
           try { 
            jObject.put("success", "true"); 
        } catch (JSONException e) { 
            e.printStackTrace(); 
            try { 
                jObject.put("success", "false"); 
            } catch (JSONException e1) { 
                e1.printStackTrace(); 
            } 
        } 
           resp.getWriter().print(jObject.toString()); 
          // resp.sendRedirect("/upload/index.jsp"); 
           workbook.close(); 
        } catch (FileUploadException e) { 
            e.printStackTrace(); 
        } catch (BiffException e) { 
            e.printStackTrace(); 
        } catch (IOException e) { 
            e.printStackTrace(); 
        }  
         
    } 

  1. package sample.server;  
  2.   
  3.   
  4. import java.io.File;  
  5. import java.io.IOException;  
  6. import java.util.Iterator;  
  7. import java.util.List;  
  8. import javax.servlet.ServletException;  
  9. import javax.servlet.http.HttpServlet;  
  10. import javax.servlet.http.HttpServletRequest;  
  11. import javax.servlet.http.HttpServletResponse;  
  12. import org.apache.commons.fileupload.FileItem;  
  13. import org.apache.commons.fileupload.FileItemFactory;  
  14. import org.apache.commons.fileupload.FileUploadException;  
  15. import org.apache.commons.fileupload.disk.DiskFileItemFactory;  
  16. import org.apache.commons.fileupload.servlet.ServletFileUpload;  
  17.   
  18. public class FileUploadServlet extends HttpServlet {  
  19.     private static final long serialVersionUID = 1L;  
  20.       
  21.     @Override  
  22.     protected void doPost(HttpServletRequest request, HttpServletResponse response)  
  23.         throws ServletException, IOException {  
  24.     // TODO Auto-generated method stub  
  25.       
  26.         response.setContentType("text/html");  
  27.         response.setCharacterEncoding("utf-8");   
  28.         FileItemFactory factory = new DiskFileItemFactory();  
  29.         ServletFileUpload upload = new ServletFileUpload(factory);       
  30.       
  31.         List items = null;       
  32.   
  33.         try {      
  34.             items = upload.parseRequest(request);       
  35.         }  
  36.         catch (FileUploadException ex) {       
  37.             ex.printStackTrace();       
  38.         }      
  39.       
  40.         Iterator iter = items.iterator();       
  41.       
  42.         while (iter.hasNext()) {       
  43.             FileItem item = (FileItem) iter.next();       
  44.        
  45.             String savePath = getServletContext().getRealPath("/uploads");  
  46.                               
  47.             String filename = item.getName();     
  48.      
  49.             String filename2 = filename.replaceAll("/", "//");  
  50.             int pos = filename.lastIndexOf( "//") + 1;  
  51.      
  52.             File file = new File(savePath,filename.substring( pos ) );   
  53.            
  54.             try {  
  55.                 item.write(file);  
  56.             }   
  57.             catch (Exception e) {     
  58.                 e.printStackTrace();  
  59.             }      
  60.         }       
  61.     }      
  62. }  

在mastplan页面加多按键,完毕上传excel文件的机能,并在保留之前读取文件内容将其保存到数据Curry面。 具体贯彻: ^_^ 先闪闪...

package sample.server; import java.io.File; import java.io.IOException; import java.util.Iterator; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileItemFactory; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; public class FileUploadServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.setContentType("text/html"); response.setCharacterEncoding("utf-8"); FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List items = null; try { items = upload.parseRequest(request); } catch (FileUploadException ex) { ex.printStackTrace(); } Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); String savePath = getServletContext().getRealPath("/uploads"); String filename = item.getName(); String filename2 = filename.replaceAll("/", "//"); int pos = filename.lastIndexOf( "//") + 1; File file = new File(savePath,filename.substring( pos ) ); try { item.write(file); } catch (Exception e) { e.printStackTrace(); } } } }

 

 

最终 最重大的一步!! 展开web.xml 出席

 

[xhtml] view plaincopyprint?

  1. <servlet>  
  2.     <servlet-name>uploadServlet</servlet-name>  
  3.     <servlet-class>sample.server.FileUploadServlet</servlet-class>  
  4.   </servlet>  
  5.     
  6.   <servlet-mapping>  
  7.     <servlet-name>uploadServlet</servlet-name>  
  8.     <url-pattern>/login/fileupload</url-pattern>  
  9.   </servlet-mapping>  

<servlet> <servlet-name>uploadServlet</servlet-name> <servlet-class>sample.server.FileUploadServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>uploadServlet</servlet-name> <url-pattern>/login/fileupload</url-pattern> </servlet-mapping>

 

多少个servlet-name 一样就可以而servlet-class对应事先拉长的劳务,url-pattern对应 client端中的

formpanel.setAction( GWT.getModuleBaseURL() + "fileupload" );

打开 xxx.gwt.xml 加入 :<servlet class="sample.server.FileUploadServlet" path="/fileupload" />

class 和 path也是应和的,别搞错啦,不然会正剧的

 

好呢能够运维试试了,上边看download

 

download轻巧一小点,client中代码:

 

[java] view plaincopyprint?

  1. void download( String filename ) {  
  2.         if( RootPanel.get("downloadiframe") != null ) {  
  3.             Widget widgetFrame = (Widget)RootPanel.get("downloadiframe");  
  4.             widgetFrame.removeFromParent();  
  5.         }   
  6.         Frame frame = new Frame( GWT.getModuleBaseURL() + "filedownload" + "?id=downloadiframe"+  
  7.                 "&filename=" + filename );  
  8.         frame.setVisible( false );  
  9.         frame.setSize( "0px", "0px" );  
  10.         RootPanel.get().add( frame );  
  11.           
  12.     }  

void download( String filename ) { if( RootPanel.get("downloadiframe") != null ) { Widget widgetFrame = (Widget)RootPanel.get("downloadiframe"); widgetFrame.removeFromParent(); } Frame frame = new Frame( GWT.getModuleBaseURL() + "filedownload" + "?id=downloadiframe"+ "&filename=" + filename ); frame.setVisible( false ); frame.setSize( "0px", "0px" ); RootPanel.get().add( frame ); }

 

 

同一新建多个 DownloadServlet.java 有了前边的阅历相信我们应该找到点头绪了吗? 代码:

 

[java] view plaincopyprint?

  1. package sample.server;  
  2.   
  3. import java.io.BufferedInputStream;  
  4. import java.io.File;  
  5. import java.io.FileInputStream;  
  6. import java.io.IOException;  
  7.   
  8. import javax.servlet.ServletException;  
  9. import javax.servlet.ServletOutputStream;  
  10. import javax.servlet.http.HttpServlet;  
  11. import javax.servlet.http.HttpServletRequest;  
  12. import javax.servlet.http.HttpServletResponse;  
  13.   
  14. import com.google.gwt.core.client.GWT;  
  15. import com.google.gwt.user.client.ui.Frame;  
  16.   
  17. public class DownloadServlet extends HttpServlet {  
  18.     private static final long serialVersionUID = 1L;  
  19.   
  20.     protected void doGet( HttpServletRequest req, HttpServletResponse resp )  
  21.         throws ServletException, IOException  
  22.     {  
  23.         //此函数对应从前的 Frame frame =   
  24.         //new Frame( GWT.getModuleBaseURL() + "filedownload" + "?id=downloadiframe"+"&filename=" + filename );  
  25.         //传文件名特别轻便啊  
  26.         String filename = req.getParameter("filename");  
  27.           
  28.         //那边你要协调整制从哪下载的文本!! 笔者是把上传路线直接给他了  
  29.         //这里说下。。笔者以前没和煦创建 uploads 结果特别正剧  
  30.         //记得在 war 路线下开创 !!  
  31.         String filepath = req.getRealPath("/uploads");  
  32.         File file = new File( filepath+"/"+filename );  
  33.   
  34.         //上边代码从网络拉的,间接抄就行了  
  35.         FileInputStream fis = new FileInputStream(file);  
  36.         resp.addHeader("Content-Disposition","attachment; filename=" + filename );  
  37.   
  38.         ServletOutputStream out = resp.getOutputStream();  
  39.         resp.setBufferSize(32768);  
  40.         int bufSize = resp.getBufferSize();  
  41.         byte[] buffer = new byte[bufSize];  
  42.         BufferedInputStream bis = new BufferedInputStream(fis,bufSize);  
  43.   
  44.         int bytes;  
  45.         while ((bytes = bis.read(buffer, 0, bufSize)) >= 0)  
  46.             out.write(buffer, 0, bytes);  
  47.         bis.close();  
  48.         fis.close();  
  49.         out.flush();  
  50.         out.close();  
  51.     }  
  52. }  

package sample.server; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.gwt.core.client.GWT; import com.google.gwt.user.client.ui.Frame; public class DownloadServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet( HttpServletRequest req, HttpServletResponse resp ) throws ServletException, IOException { //此函数对应以前的 Frame frame = //new Frame( GWT.getModuleBaseURubiconL() + "filedownload" + "?id=downloadiframe"+"&filename=" + filename ); //传文件名极其简单啊 String filename = req.getParameter("filename"); //那边你要和煦主宰从哪下载的文本!! 作者是把上传路线间接给他了 //这里说下。。笔者原先没和谐创建 uploads 结果十二分喜剧 //记得在 war 路线下创设 !! String filepath = req.getRealPath("/uploads"); File file = new File( filepath+"/"+filename ); //上边代码从互连网拉的,直接抄就行了 FileInputStream fis = new FileInputStream(file); resp.addHeader("Content-Disposition","attachment; filename=" + filename ); ServletOutputStream out = resp.getOutputStream(); resp.setBufferSize(32768); int bufSize = resp.getBufferSize(); byte[] buffer = new byte[bufSize]; BufferedInputStream bis = new BufferedInputStream(fis,bufSize); int bytes; while ((bytes = bis.read(buffer, 0, bufSize)) >= 0) out.write(buffer, 0, bytes); bis.close(); fis.close(); out.flush(); out.close(); } }

 

 

 

配备多少个xml和upload是一致的,注意别拼错字母了呀!!!!

本文由六合联盟网发布于前端技术,转载请注明出处:实现文件上传和下载,文件上传

关键词: