Servlet 實現上傳檔案以及同時,寫入xml格式檔案和上傳

來源:互聯網
上載者:User

標籤:

package com.isoftstone.eply.servlet;import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.File;import java.io.FileOutputStream;import java.io.FileWriter;import java.io.IOException;import java.io.InputStream;import java.io.PrintWriter;import java.io.StringReader;import java.util.ArrayList;import java.util.List;import java.util.Map;import java.util.UUID;import javax.activation.DataHandler;import javax.activation.DataSource;import javax.activation.FileDataSource;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.disk.DiskFileItemFactory;import org.apache.commons.fileupload.servlet.ServletFileUpload;import com.isoftstone.eply.util.ChangeFileToString;import com.isoftstone.eply.util.CheckElectronicPolicy;import com.isoftstone.eply.util.CreateCheckXml;import com.isoftstone.eply.vo.EPlyResponseFileVo;import com.isoftstone.eply.vo.EPlyResponseVo;import com.isoftstone.fwk.util.SpringUtils;public class ElectroicPolicyUploadFileServlet extends HttpServlet {    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{        this.doPost(request, response);    }    public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {        //得到上傳檔案的儲存目錄,將上傳的檔案存放於WEB-INF目錄下,不允許外界直接存取,保證上傳檔案的安全        String savePath = this.getServletContext().getContextPath()+"/upload";         File file = new File(savePath);        //判斷上傳檔案的儲存目錄是否存在        if (!file.exists() && !file.isDirectory()) {            System.out.println(savePath+"目錄不存在,需要建立");            //建立目錄            file.mkdir();        }        String message = "";//訊息提示        try{            //使用Apache檔案上傳組件處理檔案上傳步驟:            //1、建立一個DiskFileItemFactory工廠            DiskFileItemFactory factory = new DiskFileItemFactory();            //2、建立一個檔案上傳解析器            ServletFileUpload upload = new ServletFileUpload(factory);            //解決上傳檔案名稱的中文亂碼            upload.setHeaderEncoding("UTF-8");             //3、判斷提交上來的資料是否是上傳表單的資料            if(!ServletFileUpload.isMultipartContent(request)){                //按照傳統方式擷取資料                return ;            }            //4、使用ServletFileUpload解析器解析上傳資料,解析結果返回的是一個List<FileItem>集合,每一個FileItem對應一個Form表單的輸入項            List<FileItem> list = upload.parseRequest(request);            for(FileItem item : list){                //如果fileitem中封裝的是普通輸入項的資料                if(item.isFormField()){                    String name = item.getFieldName();                    //解決普通輸入項的資料的中文亂碼問題                    String value = item.getString("UTF-8");                    //value = new String(value.getBytes("iso8859-1"),"UTF-8");                    System.out.println("普通輸入項的名稱和資料"+name + "=" + value);                    CPlyNo=value;                }else{//如果fileitem中封裝的是上傳檔案                    //得到上傳的檔案名稱,                    String filename = item.getName();if(filename==null || filename.trim().equals("")){                        continue;                    }                    //注意:不同的瀏覽器提交的檔案名稱是不一樣的,有些瀏覽器提交上來的檔案名稱是帶有路徑的,如:  c:\a\b\1.txt,而有些只是單純的檔案名稱,如:1.txt                    //處理擷取到的上傳檔案的檔案名稱的路徑部分,只保留檔案名稱部分                    filename = filename.substring(filename.lastIndexOf("\\")+1);                    //擷取item中的上傳檔案filename的輸入資料流                    InputStream in = item.getInputStream();                    //建立一個檔案輸出資料流                    FileOutputStream out = new FileOutputStream(savePath + "/" + filename);                    //建立一個緩衝區                    byte buffer[] = new byte[1024];                    //判斷輸入資料流中的資料是否已經讀完的標識                    int len = 0;                    //迴圈將輸入資料流讀入到緩衝區當中,(len=in.read(buffer))>0就表示in裡面還有資料                    while((len=in.read(buffer))>0){                        //使用FileOutputStream輸出資料流將緩衝區的資料寫入到指定的目錄(savePath + "\\" + filename)當中                        out.write(buffer, 0, len);                    }                    //關閉輸入資料流                    in.close();                    //關閉輸出資料流                    out.close();                    //刪除處理檔案上傳時產生的臨時檔案                    item.delete();                                        UUID uuid = UUID.randomUUID();                    // 得到對象產生的ID                    String resid = uuid.toString(); 

            String xmldata
= "<?xml version=\"1.0\" encoding=\"GBK\"?><PACKET><HEAD><KEY>E03</KEY><BUSINESS_SOURCE>0</BUSINESS_SOURCE><NUM>1100101000108000320150000092</NUM><TYPE>A</TYPE></HEAD></PACKET>";//拼報文 File xmlFile= new File(savePath +"/"+resid+".xml");//儲存xml格式檔案 if (!xmlFile.getParentFile().exists()) xmlFile.getParentFile().mkdirs();   BufferedReader bufferedReader = new BufferedReader(new StringReader(xmldata));    BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(xmlFile));   char buf[] = new char[1024]; //字元緩衝區   int len2;   while ((len2 = bufferedReader.read(buf)) != -1) { bufferedWriter.write(buf, 0, len2); } bufferedWriter.flush(); bufferedReader.close(); bufferedWriter.close(); DataSource source = new FileDataSource(xmlFile); DataHandler dataHandler =new DataHandler(source); EPlyResponseVo epresponse=new EPlyResponseVo(); List<EPlyResponseFileVo> listvo = new ArrayList<EPlyResponseFileVo>(); File file=new File(savePath +"/"+filename); DataSource source2 = new FileDataSource(file); DataHandler dataHandler2 =new DataHandler(source2); xmlFile.delete(); //刪除臨時檔案 filepdf.delete(); //刪除臨時檔案 }catch (Exception e) { if("".equals(message)){ message = "上傳檔案失敗,請重新上傳!"; } e.printStackTrace(); } response.setContentType("text/html;charset=gb2312"); PrintWriter out=response.getWriter(); out.println("<script type=‘text/javascript‘>alert(‘"+message+"‘)</script>"); out.print("<script language=javascript>window.close();"); out.print("</script>"); out.close(); }}

 

Servlet 實現上傳檔案以及同時,寫入xml格式檔案和上傳

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.