Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //клиент. http://stackoverflow.com/questions/2017414/post-multipart-request-with-android-sdk большая часть отсюда
- import android.content.Context;
- import android.os.Environment;
- import android.util.Log;
- import java.io.*;
- import java.net.HttpURLConnection;
- import java.net.URL;
- import java.net.URLConnection;
- import java.util.zip.GZIPOutputStream;
- public class FileMultipartSender
- {
- private Context context;
- private String boundary= "==="+ System.currentTimeMillis() +"===";
- private static final String LINE_FEED="\r\n";
- private HttpURLConnection urlConnn;
- private PrintWriter writer;
- public FileMultipartSender(Context _context)
- {
- context=_context;
- }
- private void init(String requestURL,File uploadFile,String id) throws IOException
- {
- String dir= uploadFile.getParent();
- String root="";
- if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
- root= Environment.getExternalStorageDirectory().getAbsolutePath();
- dir= dir.replace(root,"");
- String date= DateUtil.dateToString(DateUtil.getCurrentDate() ) +" "+ DateUtil.timeToString(DateUtil.getCurrentDate(),true);
- URL url= new URL(requestURL);
- urlConnn= (HttpURLConnection)url.openConnection();
- urlConnn.setRequestProperty(O.yps.attrs.ID,id);
- urlConnn.setRequestProperty(O.yps.attrs.DIR,dir);
- urlConnn.setRequestProperty(O.yps.attrs.DATE,date);
- urlConnn.setRequestProperty(O.yps.attrs.ENCODING,"gzip");
- urlConnn.setDoOutput(true);
- urlConnn.setDoInput(true);
- urlConnn.setRequestProperty("Content-Type","multipart/form-data; boundary="+ boundary);
- writer= new PrintWriter(new OutputStreamWriter(urlConnn.getOutputStream(),O.CHARSET),true);
- }
- private void addFilePart(String fieldName, File uploadFile) throws IOException
- {
- String fileName= uploadFile.getName();
- writer.append("--"+ boundary + LINE_FEED);
- writer.append("Content-Disposition: form-data; name=\""+ fieldName +"\"; filename=\""+ fileName +"\""+ LINE_FEED);
- writer.append("Content-Type: "+ URLConnection.guessContentTypeFromName(fileName) + LINE_FEED);
- writer.append(LINE_FEED);
- writer.flush();
- String tempPath;
- if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED) && context.getExternalCacheDir()!=null)
- tempPath= context.getExternalCacheDir().getAbsolutePath() +"/955653 Temp.gz";
- else
- tempPath= context.getCacheDir().getAbsolutePath() +"/955653 Temp.gz";
- File tempFile= new File(tempPath);
- byte buff[]= new byte[4096];
- int count;
- try
- {
- BufferedInputStream fileIn= new BufferedInputStream(new FileInputStream(uploadFile) );
- BufferedOutputStream gzipOut= new BufferedOutputStream(new GZIPOutputStream(new FileOutputStream(tempFile) ) );
- while( (count=fileIn.read(buff) )>0)
- gzipOut.write(buff,0,count);
- gzipOut.flush();
- gzipOut.close();
- fileIn.close();
- BufferedInputStream gzipIn= new BufferedInputStream(new FileInputStream(tempFile) );
- BufferedOutputStream urlOut= new BufferedOutputStream(urlConnn.getOutputStream() );
- while( (count=gzipIn.read(buff) )>0)
- urlOut.write(buff,0,count);
- urlOut.flush();
- gzipIn.close();
- }
- finally
- {
- tempFile.delete();
- }
- writer.append(LINE_FEED);
- }
- private String finish() throws IOException
- {
- StringBuilder sb= new StringBuilder();
- writer.append(LINE_FEED).flush();
- writer.append("--"+ boundary +"--"+ LINE_FEED);
- writer.close();
- int status= urlConnn.getResponseCode();
- if(status==200)
- {
- BufferedReader resultIn= new BufferedReader(new InputStreamReader(urlConnn.getInputStream() ) );
- String line;
- while( (line=resultIn.readLine() )!=null)
- sb.append(line +"\n");
- resultIn.close();
- urlConnn.disconnect();
- }
- else
- throw new IOException("Server returned non-OK status: " + status);
- return sb.toString();
- }
- public String sendFile(String requestURL, File uploadFile,String id) throws IOException
- {
- try
- {
- init(requestURL,uploadFile,id);
- }
- catch(IOException initErr)
- {
- Log.d(O.TAG,"sendFile: ошибка инициализаций");
- throw initErr;
- }
- try
- {
- String fieldName="file";
- addFilePart(fieldName,uploadFile);
- }
- catch(IOException writeErr)
- {
- writeErr.printStackTrace();
- Log.d(O.TAG,"sendFile: ошибка записи файла в поток");
- throw writeErr;
- }
- String response;
- try
- {
- response= finish();
- }
- catch(IOException responseErr)
- {
- Log.d(O.TAG,"sendFile: Ошибка ответа сервера");
- throw responseErr;
- }
- return response;
- }
- }
- ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- //сервер. Пара мыслей отсюда http://stackoverflow.com/questions/2422468/how-to-upload-files-to-server-using-jsp-servlet?lq=1
- import javax.servlet.ServletException;
- import javax.servlet.annotation.MultipartConfig;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import javax.servlet.http.Part;
- import java.io.*;
- import java.util.zip.GZIPInputStream;
- @MultipartConfig
- public class FileReceiver extends HttpServlet
- {
- @Override
- protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException
- {
- response.setCharacterEncoding(O.CHARSET);
- response.setContentType("text/plain; charset="+ O.CHARSET);
- String path;
- String id;
- String dir;
- id= request.getHeader(O.attr.ID);
- if(id==null)
- id= O.defaults.ID;
- dir= request.getHeader(O.attr.DIR);
- if(dir==null)
- dir= O.defaults.DIR;
- path= O.MAIN_DIR +"/"+ id + dir;
- File dirCheck= new File(path);
- if(!dirCheck.exists() )
- dirCheck.mkdirs();
- Part filePart= request.getPart("file");
- long fileSize= filePart.getSize();
- String fileName= filePart.getSubmittedFileName();
- String contentEncoding= request.getHeader(O.attr.ENCODING);
- BufferedInputStream fileIn= new BufferedInputStream(filePart.getInputStream() );
- path+= "/"+ fileName;
- if(contentEncoding!=null && contentEncoding.equals("gzip") )
- path+=".gz";
- BufferedOutputStream fileOut= new BufferedOutputStream(new FileOutputStream(path) );
- byte buff[]= new byte[4096];
- int count;
- while( (count=fileIn.read(buff) )>0)
- fileOut.write(buff,0,count);
- fileOut.flush();
- fileOut.close();
- fileIn.close();
- if(contentEncoding!=null && contentEncoding.equals("gzip") )
- {
- BufferedInputStream gzipIn;
- BufferedOutputStream gzipOut;
- File tempFile;
- tempFile= new File(path);
- path= dirCheck.getAbsolutePath() +"/"+ fileName;
- gzipIn= new BufferedInputStream(new GZIPInputStream(new FileInputStream(tempFile) ) );
- gzipOut= new BufferedOutputStream(new FileOutputStream(path) );
- while( (count=gzipIn.read(buff) )>=0)
- gzipOut.write(buff,0,count);
- gzipOut.flush();
- gzipOut.close();
- gzipIn.close();
- tempFile.delete();
- }
- response.getWriter().write("Файл "+ fileName +" загружен успешно. Размер файла: "+ fileSize);
- }
- }
Add Comment
Please, Sign In to add comment