java web 上传保存xml文件

 java程序和接收的servlet如下:  
  package   com.swt.test;  
   
  import   java.io.DataInputStream;  
  import   java.io.File;  
  import   java.io.FileInputStream;  
  import   java.io.InputStream;  
  import   java.io.OutputStream;  
  import   java.net.HttpURLConnection;  
  import   java.net.URL;  
   
  public   class   UploadXMLFile   {  
   
          /**  
            *   上传xml文件  
            *    
            *   @param   strFile  
            *                         上传带绝对路径的文件名  
            *   @param   strURL  
            *   @return   result   上传成功,result="SUCCESS",其他则为出错信息。  
            */  
          public   synchronized   String   uploadXMLFile(final   String   strFile,   final   String   strURL)   {  
   
                  String   result   =   null;  
   
                  try   {  
                          URL   url   =   new   URL(strURL   +   "?filename="   +   strFile);  
                          HttpURLConnection   conn   =   (HttpURLConnection)   url.openConnection();  
                          conn.setDoOutput(true);  
                          conn.setDoInput(true);  
                          conn.setUseCaches(false);  
                          conn.setRequestProperty("enctype",   "multipart/form-data");  
                          conn.setRequestProperty("contentType",   "charset=GBK");  
                          conn.setRequestMethod("POST");  
   
                          //上传xml文件  
                          DataInputStream   file   =   new   DataInputStream(new   FileInputStream(  
                                          new   File(strFile)));  
                          OutputStream   out   =   conn.getOutputStream();  
                          int   bytesOut   =   0;  
                          byte[]   bufferOut   =   new   byte[8192];  
                          while   ((bytesOut   =   file.read(bufferOut,   0,   8192))   !=   -1)   {  
                                  out.write(bufferOut,   0,   bytesOut);//  
                          }  
                          out.flush();  
                          out.close();  
   
                          //获得上传的结果  
                          InputStream   isResult   =   conn.getInputStream();  
                          byte[]   buffer   =   new   byte[isResult.available()];  
                          isResult.read(buffer);  
                          result   =   new   String(buffer);  
                          isResult.close();  
   
                  }   catch   (Exception   e)   {  
                          result   =   "ERROR";  
                          System.out.println(e.getMessage());  
                  }  
                  return   result;  
          }  
   
          public   static   void   main(String[]   args)   {  
                  UploadXMLFile   uxf   =   new   UploadXMLFile();  
                  System.out.println("上传文件结果");  
                  String   sb   =   uxf.uploadXMLFile("D://swt.xml",  
                                  "http://localhost:8080/beh/xml.163");  
                  System.out.println(sb);  
   
          }  
   
  }  
   
   
  接收的servlet  
  package   com.swt.servlet;  
   
  import   java.io.BufferedReader;  
  import   java.io.BufferedWriter;  
  import   java.io.File;  
  import   java.io.FileNotFoundException;  
  import   java.io.FileOutputStream;  
  import   java.io.IOException;  
  import   java.io.InputStream;  
  import   java.io.ObjectInputStream;  
  import   java.io.OutputStream;  
  import   java.io.PrintWriter;  
  import   java.io.UnsupportedEncodingException;  
   
  import   javax.servlet.ServletException;  
  import   javax.servlet.ServletInputStream;  
  import   javax.servlet.http.HttpServlet;  
  import   javax.servlet.http.HttpServletRequest;  
  import   javax.servlet.http.HttpServletResponse;  
   
  import   org.apache.commons.logging.Log;  
  import   org.apache.commons.logging.LogFactory;  
   
   
  /**  
    *  
    *   @author   sweater  
    */  
  public   class   GetXMLFile   extends   HttpServlet   {  
   
           
          private   final   static   Log   log   =   LogFactory.getLog(LoginAction.class);  
           
          /**  
            *   Constructor   of   the   object.  
            */  
          public   GetXMLFile()   {  
                  super();  
          }  
   
          /**  
            *   Destruction   of   the   servlet.   <br>  
            */  
          public   void   destroy()   {  
                  super.destroy();   //   Just   puts   "destroy"   string   in   log  
                  //   Put   your   code   here  
          }  
   
          /**  
            *   The   doPost   method   of   the   servlet.   <br>  
            *  
            *   This   method   is   called   when   a   form   has   its   tag   value   method   equals   to   post.  
            *    
            *   @param   request   the   request   send   by   the   client   to   the   server  
            *   @param   response   the   response   send   by   the   server   to   the   client  
            *   @throws   ServletException   if   an   error   occurred  
            *   @throws   IOException   if   an   error   occurred  
            */  
          public   void   doPost(HttpServletRequest   request,   HttpServletResponse   response)  
                          throws   ServletException,   IOException   {  
                   
                  System.out.println(this.getClass());  
                  //System.out.println((String)request.getParameter("filename"));            
   
  response.setContentType("text/html");  
  PrintWriter   outResult   =   null;  
                  try   {  
                          outResult   =   response.getWriter();  
                  }   catch   (IOException   ioE)   {  
                  }  
                   
                  String   saveFile   =   "D://get.xml";//""";  
                  String   uploadReult   =   "ERROR";  
                  int   reqStreamLen   =   request.getContentLength();  
                  BufferedReader   readFile   =   null;  
                  BufferedWriter   writeFile   =   null;  
                   
                  try   {  
                          InputStream   is   =   request.getInputStream();  
                          OutputStream   os   =   new   FileOutputStream(saveFile);//建立一个上传文件的输出流"D://get.xml"  
                          int   bytesRead   =   0;  
                          byte[]   buffer   =   new   byte[8192];  
                          while   ((bytesRead   =   is.read(buffer,   0,   8192))   !=   -1)   {  
                                  os.write(buffer,   0,   bytesRead);//传过来的文件写入文件  
                                  //System.out.println(new   String(buffer));  
                          }  
                          os.flush();  
                          os.close();  
                          is.close();  
   
                  }   catch   (UnsupportedEncodingException   e)   {  
                          uploadReult   =   "UnsupportedEncodingException";  
                          log.info(e.getMessage());  
                          e.printStackTrace();  
                  }   catch   (FileNotFoundException   e)   {  
                          uploadReult   =   "FileNotFoundException";  
                          log.info(e.getMessage());  
                          e.printStackTrace();  
                  }   catch   (IOException   e)   {  
                          uploadReult   =   "IOException";  
                          log.info(e.getMessage());  
                          e.printStackTrace();  
                  }  
                   
                  String   uploadFile   =   (String)request.getParameter("filename");                  
                  File   file   =   new   File(saveFile);  
                  log.info(String.valueOf(file.length()));  
                  log.info(String.valueOf(reqStreamLen));  
                  if(file.exists()&&(file.length()==reqStreamLen)){  
                          uploadReult   =   "SUCCESS";  
                          log.info(request.getRemoteAddr()   +   "上传文件:"   +   uploadFile   +   "   成功");  
                  }else{  
                          uploadReult   =   "ERROR";  
                          log.info(request.getRemoteAddr()   +   "上传文件:"   +   uploadFile   +   "   失败");  
                  }  
                   
                  outResult.println(uploadReult);  
                  outResult.flush();  
                  outResult.close();  
                   
          }  
           
          public   void   doGet(HttpServletRequest   request,   HttpServletResponse   response)  
          throws   ServletException,   IOException   {  
                this.doPost(request,response);  
          }  
   
   
          /**  
            *   Initialization   of   the   servlet.   <br>  
            *  
            *   @throws   ServletException   if   an   error   occure  
            */  
          public   void   init()   throws   ServletException   {  
   
          }  
   
  }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是Java上传XML文件的示例代码: ```java import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import javax.servlet.ServletException; import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.Part; @WebServlet("/upload") @MultipartConfig public class UploadServlet extends HttpServlet { private static final long serialVersionUID = 1L; private static final String UPLOAD_DIR = "uploads"; @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //获取上传文件的目录 String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIR; File uploadDir = new File(uploadPath); if (!uploadDir.exists()) { uploadDir.mkdir(); } //获取上传的文件 Part filePart = request.getPart("file"); String fileName = getFileName(filePart); Path filePath = Paths.get(uploadPath, fileName); Files.copy(filePart.getInputStream(), filePath); //处理上传的文件 //TODO response.getWriter().append("File uploaded successfully!"); } private String getFileName(final Part part) { final String partHeader = part.getHeader("content-disposition"); for (String content : partHeader.split(";")) { if (content.trim().startsWith("filename")) { return content.substring(content.indexOf('=') + 1).trim().replace("\"", ""); } } return null; } } ``` 在上面的代码中,我们使用了Servlet 3.0提供的@MultipartConfig注解来支持文件上传。该注解表明该Servlet支持文件上传,并且指定上传文件的临时目录。在doPost方法中,我们首先获取上传文件的目录,如果该目录不存在则创建。然后获取上传的文件,将其保存到指定的目录中。最后我们可以在处理上传的文件之前,将上传的文件名输出到控制台上。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值