Guest User

Untitled

a guest
May 10th, 2016
223
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 7.25 KB | None | 0 0
  1. //клиент. http://stackoverflow.com/questions/2017414/post-multipart-request-with-android-sdk большая часть отсюда
  2. import android.content.Context;
  3. import android.os.Environment;
  4. import android.util.Log;
  5. import java.io.*;
  6. import java.net.HttpURLConnection;
  7. import java.net.URL;
  8. import java.net.URLConnection;
  9. import java.util.zip.GZIPOutputStream;
  10.  
  11. public class FileMultipartSender
  12.     {
  13.      private Context context;
  14.      private String boundary= "==="+ System.currentTimeMillis() +"===";
  15.      private static final String LINE_FEED="\r\n";
  16.      private HttpURLConnection urlConnn;
  17.      private PrintWriter writer;
  18.  
  19.      public FileMultipartSender(Context _context)
  20.         {
  21.          context=_context;
  22.          }
  23.     private void init(String requestURL,File uploadFile,String id) throws IOException
  24.         {
  25.          String dir= uploadFile.getParent();
  26.          String root="";
  27.          if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
  28.              root= Environment.getExternalStorageDirectory().getAbsolutePath();
  29.          dir= dir.replace(root,"");
  30.          String date= DateUtil.dateToString(DateUtil.getCurrentDate() ) +" "+ DateUtil.timeToString(DateUtil.getCurrentDate(),true);
  31.          URL url= new URL(requestURL);
  32.          urlConnn= (HttpURLConnection)url.openConnection();
  33.          urlConnn.setRequestProperty(O.yps.attrs.ID,id);
  34.          urlConnn.setRequestProperty(O.yps.attrs.DIR,dir);
  35.          urlConnn.setRequestProperty(O.yps.attrs.DATE,date);
  36.          urlConnn.setRequestProperty(O.yps.attrs.ENCODING,"gzip");
  37.          urlConnn.setDoOutput(true);
  38.          urlConnn.setDoInput(true);
  39.          urlConnn.setRequestProperty("Content-Type","multipart/form-data; boundary="+ boundary);
  40.          writer= new PrintWriter(new OutputStreamWriter(urlConnn.getOutputStream(),O.CHARSET),true);
  41.          }
  42.  
  43.      private void addFilePart(String fieldName, File uploadFile) throws IOException
  44.         {
  45.          String fileName= uploadFile.getName();
  46.          writer.append("--"+ boundary + LINE_FEED);
  47.          writer.append("Content-Disposition: form-data; name=\""+ fieldName +"\"; filename=\""+ fileName +"\""+ LINE_FEED);
  48.          writer.append("Content-Type: "+ URLConnection.guessContentTypeFromName(fileName) + LINE_FEED);
  49.          writer.append(LINE_FEED);
  50.          writer.flush();
  51.  
  52.          String tempPath;
  53.          if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED) && context.getExternalCacheDir()!=null)
  54.              tempPath= context.getExternalCacheDir().getAbsolutePath() +"/955653 Temp.gz";
  55.          else
  56.              tempPath= context.getCacheDir().getAbsolutePath() +"/955653 Temp.gz";
  57.          File tempFile= new File(tempPath);
  58.          byte buff[]= new byte[4096];
  59.          int count;
  60.          try
  61.             {
  62.              BufferedInputStream fileIn= new BufferedInputStream(new FileInputStream(uploadFile) );
  63.              BufferedOutputStream gzipOut= new BufferedOutputStream(new GZIPOutputStream(new FileOutputStream(tempFile) ) );
  64.              while( (count=fileIn.read(buff) )>0)
  65.                  gzipOut.write(buff,0,count);
  66.              gzipOut.flush();
  67.              gzipOut.close();
  68.              fileIn.close();
  69.  
  70.              BufferedInputStream gzipIn= new BufferedInputStream(new FileInputStream(tempFile) );
  71.              BufferedOutputStream urlOut= new BufferedOutputStream(urlConnn.getOutputStream() );
  72.              while( (count=gzipIn.read(buff) )>0)
  73.                  urlOut.write(buff,0,count);
  74.              urlOut.flush();
  75.              gzipIn.close();
  76.              }
  77.          finally
  78.             {
  79.              tempFile.delete();
  80.              }
  81.          writer.append(LINE_FEED);
  82.          }
  83.      private String finish() throws IOException
  84.         {
  85.          StringBuilder sb= new StringBuilder();
  86.          writer.append(LINE_FEED).flush();
  87.          writer.append("--"+ boundary +"--"+ LINE_FEED);
  88.          writer.close();
  89.          int status= urlConnn.getResponseCode();
  90.          if(status==200)
  91.             {
  92.              BufferedReader resultIn= new BufferedReader(new InputStreamReader(urlConnn.getInputStream() ) );
  93.              String line;
  94.              while( (line=resultIn.readLine() )!=null)
  95.                  sb.append(line +"\n");
  96.              resultIn.close();
  97.              urlConnn.disconnect();
  98.              }
  99.          else
  100.              throw new IOException("Server returned non-OK status: " + status);
  101.          return sb.toString();
  102.          }
  103.  
  104.      public String sendFile(String requestURL, File uploadFile,String id) throws IOException
  105.         {
  106.          try
  107.             {
  108.              init(requestURL,uploadFile,id);
  109.              }
  110.          catch(IOException initErr)
  111.             {
  112.              Log.d(O.TAG,"sendFile: ошибка инициализаций");
  113.              throw initErr;
  114.              }
  115.          try
  116.             {
  117.              String fieldName="file";
  118.              addFilePart(fieldName,uploadFile);
  119.              }
  120.          catch(IOException writeErr)
  121.             {
  122.              writeErr.printStackTrace();
  123.              Log.d(O.TAG,"sendFile: ошибка записи файла в поток");
  124.              throw writeErr;
  125.              }
  126.          String response;
  127.          try
  128.             {
  129.              response= finish();
  130.              }
  131.          catch(IOException responseErr)
  132.             {
  133.              Log.d(O.TAG,"sendFile: Ошибка ответа сервера");
  134.              throw responseErr;
  135.              }
  136.          return response;
  137.          }
  138.      }
  139.  
  140. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  141.  
  142. //сервер. Пара мыслей отсюда http://stackoverflow.com/questions/2422468/how-to-upload-files-to-server-using-jsp-servlet?lq=1
  143. import javax.servlet.ServletException;
  144. import javax.servlet.annotation.MultipartConfig;
  145. import javax.servlet.http.HttpServlet;
  146. import javax.servlet.http.HttpServletRequest;
  147. import javax.servlet.http.HttpServletResponse;
  148. import javax.servlet.http.Part;
  149. import java.io.*;
  150. import java.util.zip.GZIPInputStream;
  151.  
  152. @MultipartConfig
  153. public class FileReceiver extends HttpServlet
  154.     {
  155.      @Override
  156.      protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException
  157.         {
  158.          response.setCharacterEncoding(O.CHARSET);
  159.          response.setContentType("text/plain; charset="+ O.CHARSET);
  160.          String path;
  161.          String id;
  162.          String dir;
  163.          id= request.getHeader(O.attr.ID);
  164.          if(id==null)
  165.              id= O.defaults.ID;
  166.          dir= request.getHeader(O.attr.DIR);
  167.          if(dir==null)
  168.              dir= O.defaults.DIR;
  169.          path= O.MAIN_DIR +"/"+ id + dir;
  170.          File dirCheck= new File(path);
  171.          if(!dirCheck.exists() )
  172.              dirCheck.mkdirs();
  173.          Part filePart= request.getPart("file");
  174.          long fileSize= filePart.getSize();
  175.          String fileName= filePart.getSubmittedFileName();
  176.          String contentEncoding= request.getHeader(O.attr.ENCODING);
  177.          BufferedInputStream fileIn= new BufferedInputStream(filePart.getInputStream() );
  178.          path+= "/"+ fileName;
  179.          if(contentEncoding!=null && contentEncoding.equals("gzip") )
  180.              path+=".gz";
  181.          BufferedOutputStream fileOut= new BufferedOutputStream(new FileOutputStream(path) );
  182.  
  183.          byte buff[]= new byte[4096];
  184.          int count;
  185.          while( (count=fileIn.read(buff) )>0)
  186.              fileOut.write(buff,0,count);
  187.          fileOut.flush();
  188.          fileOut.close();
  189.          fileIn.close();
  190.  
  191.          if(contentEncoding!=null && contentEncoding.equals("gzip") )
  192.             {
  193.              BufferedInputStream gzipIn;
  194.              BufferedOutputStream gzipOut;
  195.              File tempFile;
  196.              tempFile= new File(path);
  197.              path= dirCheck.getAbsolutePath() +"/"+ fileName;
  198.              gzipIn= new BufferedInputStream(new GZIPInputStream(new FileInputStream(tempFile) ) );
  199.              gzipOut= new BufferedOutputStream(new FileOutputStream(path) );
  200.              while( (count=gzipIn.read(buff) )>=0)
  201.                  gzipOut.write(buff,0,count);
  202.              gzipOut.flush();
  203.              gzipOut.close();
  204.              gzipIn.close();
  205.              tempFile.delete();
  206.              }
  207.          response.getWriter().write("Файл "+ fileName +" загружен успешно. Размер файла: "+ fileSize);
  208.          }
  209.      }
Add Comment
Please, Sign In to add comment