安卓上传文件到服务器

来源:互联网 发布:nyaa的域名 编辑:程序博客网 时间:2024/04/28 20:18
package com.example.moon;




import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;


import android.widget.Toast;
public class Upload{
    private String end="\r\n";
    private String twoHyphens="--";
    private String boundary="******";
    private String actionUrl;
    private String theUploadPath;
    private String moodReturn;
    public Upload(String actionUrl,String theUploadPath){
        this.actionUrl=actionUrl;
    this.theUploadPath=theUploadPath;
    }
    public String getContion() throws IOException{
       String uploadUrl = actionUrl;
       String srcPath=theUploadPath;
       String end = "\r\n";
       String twoHyphens = "--";
       String boundary = "******";
       try
       {
         URL url = new URL(uploadUrl);
         HttpURLConnection httpURLConnection = (HttpURLConnection) url
             .openConnection();
         httpURLConnection.setDoInput(true);
         httpURLConnection.setDoOutput(true);
         httpURLConnection.setUseCaches(false);
         httpURLConnection.setRequestMethod("POST");
         httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
         httpURLConnection.setRequestProperty("Charset", "UTF-8");
         httpURLConnection.setRequestProperty("Content-Type",
             "multipart/form-data;boundary=" + boundary);


         DataOutputStream dos = new DataOutputStream(httpURLConnection
             .getOutputStream());
         dos.writeBytes(twoHyphens + boundary + end);
         dos
             .writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\""
                 + srcPath.substring(srcPath.lastIndexOf("/") + 1)
                 + "\"" + end);
         dos.writeBytes(end);


         FileInputStream fis = new FileInputStream(srcPath);
         byte[] buffer = new byte[8192]; // 8k
         int count = 0;
         while ((count = fis.read(buffer)) != -1)
         {
           dos.write(buffer, 0, count);


         }
         fis.close();


         dos.writeBytes(end);
         dos.writeBytes(twoHyphens + boundary + twoHyphens + end);
         dos.flush();


         InputStream is = httpURLConnection.getInputStream();
         InputStreamReader isr = new InputStreamReader(is, "utf-8");
         BufferedReader br = new BufferedReader(isr);
         String result = br.readLine();


        
          dos.close();
          is.close();
       
               return result;
       } catch (Exception e)
       {
         e.printStackTrace();
         return "error";
       }


     }
    
    public String get_moodReturn()
    {
    return theUploadPath;
    }
    

}



服务器的servlet

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
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.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;


  
/** 
 * Servlet implementation class ReceivePictureFromAndroid 
 */  
 
public class upload extends HttpServlet {  
    private static final long serialVersionUID = 1L;  
         
    public upload() {  
        super();  
    }  
  
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
    }  
  
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
              
        try {  
          DiskFileItemFactory factory = new DiskFileItemFactory();  
          ServletFileUpload upload = new ServletFileUpload(factory);  
          List<FileItem> list = upload.parseRequest(request);  
          System.out.println(list + " list " + list.size() );  
          for(FileItem item : list) {  
              String paramName = item.getFieldName();  
              System.out.println(paramName);  
              String paramValue = item.getString();  
             // System.out.println(paramValue);  //��ӡ�ǷǷ���
              if(item.isFormField() == false) {  
             String path=this.getServletContext().getRealPath("/upload");
             File pathFile= new File(path);
             if(!pathFile.exists())
             pathFile.mkdir();
                  File f = new File(path+"/love.wav");
                  item.write(f);
                  System.out.println(path);
                  System.out.println("write filt success");  
             
                  PrintWriter out=response.getWriter();
                  out.println("successt);
              }  
          }  
        } catch (Exception e) {     
            e.printStackTrace();  
        }  
    }  
  
}  

原创粉丝点击