zoukankan      html  css  js  c++  java
  • android form表单上传文件

    原文地址:http://menuz.iteye.com/blog/1282097

    Android程序使用http上传文件 

    有时,在网络编程过程中需要向服务器上传文件。Multipart/form-data是上传文件的一种方式。 

    Multipart/form-data其实就是浏览器用表单上传文件的方式。最常见的情境是:在写邮件时,向邮件后添加附件,附件通常使用表单添加,也就是用multipart/form-data格式上传到服务器。 


    Html代码  收藏代码
    1. <form action=“/TestWeb/command=UpdatePicture” method=”post” enctype=”multipart/form-data”>  
    2.     <input type=”file” name=”uploadfile1”/><br>  
    3.     <input type=”file” name=”uploadfile2”/><br>  
    4.     <input type=”submit” value=”uploadfile”>  
    5. </form>  





    内容如下: 
    Type:multipart/form-data; boundary=-----------------------------265001916915724
     
    -----------------------------265001916915724 
    Content-Disposition: form-data; name="uploadfile1"; filename="web.txt" 
    Content-Type: text/plain 

    ChinaNetSNWide  
    å­ç½‘æŽ©ç 255.255.255.255 简单的说四个255是全广播IP地址。就是用来从DHCP服     务器那里莕取IP地址。 
    默认网关0.0.0.0 即本机 

    -----------------------------265001916915724 
    Content-Disposition: form-data; name="uploadfile2"; filename="20080116064637581.jpg" 
    Content-Type: image/jpeg 

    ÿØÿà 

    -----------------------------265001916915724— 


    注意点一: 
          Header 下面boundary 有27个 -(横杆) 
          POST Data 下面传输每个文件的开头是有29个 - 
    注意点二: 
          观察POST Data可以发现从第一个-----------------------------265001916915724 
          到第二个-----------------------------265001916915724之间为一个txt文件的相关 
          信息。 
    上面form提交的servlet不用实现,只是解析了http协议,为下面模拟铺垫。 

    下面实现android客户端上传图片到服务端的servlet 
    android客户端代码 

    Java代码  收藏代码
    1. public void upload() {  
    2.        Log.d(TAG, "upload begin");  
    3.        HttpURLConnection connection = null;  
    4.        DataOutputStream dos = null;  
    5.        FileInputStream fin = null;  
    6.          
    7.        String boundary = "---------------------------265001916915724";  
    8.        // 真机调试的话,这里url需要改成电脑ip  
    9.        // 模拟机用10.0.0.2,127.0.0.1被tomcat占用了  
    10.        String urlServer = "http://10.0.0.2:8080/TestWeb/command=UpdatePicture";  
    11.        String lineEnd = " ";  
    12.        String pathOfPicture = "/sdcard/aaa.jpg";  
    13.        int bytesAvailable, bufferSize, bytesRead;  
    14.        int maxBufferSize = 1*1024*512;  
    15.        byte[] buffer = null;  
    16.          
    17.        try {  
    18.            Log.d(TAG, "try");  
    19.            URL url = new URL(urlServer);  
    20.            connection = (HttpURLConnection) url.openConnection();  
    21.              
    22.            // 允许向url流中读写数据  
    23.            connection.setDoInput(true);  
    24.            connection.setDoOutput(true);  
    25.            connection.setUseCaches(true);  
    26.              
    27.            // 启动post方法  
    28.            connection.setRequestMethod("POST");  
    29.              
    30.            // 设置请求头内容  
    31.            connection.setRequestProperty("connection""Keep-Alive");  
    32.            connection.setRequestProperty("Content-Type""text/plain");  
    33.              
    34.            // 伪造请求头  
    35.            connection.setRequestProperty("Content-Type""multipart/form-data; boundary=" + boundary);  
    36.            
    37.             
    38.            // 开始伪造POST Data里面的数据  
    39.            dos = new DataOutputStream(connection.getOutputStream());  
    40.            fin = new FileInputStream(pathOfPicture);  
    41.              
    42.            Log.d(TAG, "开始上传images");  
    43.            //--------------------开始伪造上传images.jpg的信息-----------------------------------  
    44.            String fileMeta = "--" + boundary + lineEnd +  
    45.                            "Content-Disposition: form-data; name="uploadedPicture"; filename="" + pathOfPicture + """ + lineEnd +  
    46.                            "Content-Type: image/jpeg" + lineEnd + lineEnd;  
    47.            // 向流中写入fileMeta  
    48.            dos.write(fileMeta.getBytes());  
    49.              
    50.            // 取得本地图片的字节流,向url流中写入图片字节流  
    51.            bytesAvailable = fin.available();  
    52.            bufferSize = Math.min(bytesAvailable, maxBufferSize);  
    53.            buffer = new byte[bufferSize];  
    54.              
    55.            bytesRead = fin.read(buffer, 0, bufferSize);  
    56.            while(bytesRead > 0) {  
    57.                dos.write(buffer, 0, bufferSize);  
    58.                bytesAvailable = fin.available();  
    59.                bufferSize = Math.min(bytesAvailable, maxBufferSize);  
    60.                bytesRead = fin.read(buffer, 0, bufferSize);  
    61.            }  
    62.            dos.writeBytes(lineEnd+lineEnd);  
    63.            //--------------------伪造images.jpg信息结束-----------------------------------  
    64.            Log.d(TAG, "结束上传");  
    65.              
    66.            // POST Data结束  
    67.            dos.writeBytes("--" + boundary + "--");  
    68.              
    69.            // Server端返回的信息  
    70.            System.out.println("" + connection.getResponseCode());  
    71.            System.out.println("" + connection.getResponseMessage());  
    72.              
    73.            if (dos != null) {  
    74.                dos.flush();  
    75.                dos.close();  
    76.            }  
    77.            Log.d(TAG, "upload success-----------------------------------------");  
    78.        } catch (Exception e) {  
    79.           e.printStackTrace();  
    80.           Log.d(TAG, "upload fail");  
    81.        }  
    82.    }  



    服务端servlet 

    Java代码  收藏代码
      1. import java.io.File;  
      2. import java.io.IOException;  
      3. import java.util.List;  
      4.   
      5. import javax.servlet.ServletException;  
      6. import javax.servlet.annotation.WebServlet;  
      7. import javax.servlet.http.HttpServlet;  
      8. import javax.servlet.http.HttpServletRequest;  
      9. import javax.servlet.http.HttpServletResponse;  
      10.   
      11. // 利用该组件进行接收客户端上传的文件  
      12. // 需要自己加载commons-fileupload-1.2.2.jar和commons-io-2.1.jar  
      13. import org.apache.commons.fileupload.FileItem;  
      14. import org.apache.commons.fileupload.disk.DiskFileItemFactory;  
      15. import org.apache.commons.fileupload.servlet.ServletFileUpload;  
      16.   
      17. /** 
      18.  * Servlet implementation class ReceivePictureFromAndroid 
      19.  */  
      20. @WebServlet("/command=UpdatePicture")  
      21. public class ReceivePictureFromAndroid extends HttpServlet {  
      22.     private static final long serialVersionUID = 1L;  
      23.          
      24.     public ReceivePictureFromAndroid() {  
      25.         super();  
      26.     }  
      27.   
      28.     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
      29.     }  
      30.   
      31.     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
      32.               
      33.         try {  
      34.           DiskFileItemFactory factory = new DiskFileItemFactory();  
      35.           ServletFileUpload upload = new ServletFileUpload(factory);  
      36.           List<FileItem> list = upload.parseRequest(request);  
      37.           System.out.println(list + " list " + list.size() );  
      38.           for(FileItem item : list) {  
      39.               String paramName = item.getFieldName();  
      40.               System.out.println(paramName);  
      41.               String paramValue = item.getString();  
      42.               System.out.println(paramValue);  
      43.               if(item.isFormField() == false) {  
      44.                   File f = new File("f:\img.jpg");  
      45.                   item.write(f);  
      46.                    System.out.println("write filt success");  
      47.               }  
      48.           }  
      49.         } catch (Exception e) {     
      50.             e.printStackTrace();  
      51.         }  
      52.     }  
      53.   
      54. }  
  • 相关阅读:
    Ubuntu下Nginx安装
    vi基本状态
    07. 背景图片距离
    06. 用css实现三角形
    Leetcode刷题 (二)
    Leetcode刷题 (一)
    目标检测中的AP计算
    python 引用(import)文件夹下的py文件
    git 上传和克隆文件
    Windows系统下Pytorch与python版本不匹配导致模块包导入错误
  • 原文地址:https://www.cnblogs.com/zyppac/p/3784283.html
Copyright © 2011-2022 走看看