주간 베스트 월간 베스트 3개월 베스트 베스트 게시물
꽃배달 한국, 중국 전지역배송

android fileupload with servlet

hmily1314 | 2013.06.05 13:00:02 댓글: 0 조회: 2038 추천: 0
분류웹 프로그래밍 https://life.moyiza.kr/itstudy/1856747



client source

private String newName = "1.jpg";
 
 private String uploadFile = "/sdcard/forlder/1.jpg";
 private String actionUrl = "http://ipadress:8080/TServer/Test";

 private void uploadFile() {
  String end = "\r\n";
  String twoHyphens = "--";
  String boundary = "*****";
  try {
   URL url = new URL(actionUrl);
   HttpURLConnection con = (HttpURLConnection) url.openConnection();
   con.setDoInput(true);
   con.setDoOutput(true);
   con.setUseCaches(false);
   con.setRequestMethod("POST");
   con.setRequestProperty("Connection", "Keep-Alive");
   con.setRequestProperty("Charset", "UTF-8");
   con.setRequestProperty("Content-Type",
     "multipart/form-data;boundary=" + boundary);
   DataOutputStream ds = new DataOutputStream(con.getOutputStream());
   ds.writeBytes(twoHyphens + boundary + end);
   ds.writeBytes("Content-Disposition: form-data; "
     + "name=\"file1\";filename=\"" + newName + "\"" + end);
   ds.writeBytes(end);
   FileInputStream fStream = new FileInputStream(uploadFile);
   int bufferSize = 1024;
   byte[] buffer = new byte[bufferSize];
   int length = -1;
   while ((length = fStream.read(buffer)) != -1) {
    ds.write(buffer, 0, length);
   }
   ds.writeBytes(end);
   ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
   fStream.close();
   ds.flush();
   InputStream is = con.getInputStream();
   int ch;
   StringBuffer b = new StringBuffer();
   while ((ch = is.read()) != -1) {
    b.append((char) ch);
   }
   
   Log.e("upload success", b.toString().trim());
   ds.close();
  } catch (Exception e) {
   Log.e("upload failed", e.toString().trim());
  }

servlet source

String temp = request.getSession().getServletContext().getRealPath("/")
    + "temp"; //
  System.out.println("temp=" + temp);
  String loadpath = request.getSession().getServletContext()
    .getRealPath("/")
    + "Image"; //
  System.out.println("loadpath=" + loadpath);
  DiskFileUpload fu = new DiskFileUpload();
  fu.setSizeMax(1 * 1024 * 1024); //
  fu.setSizeThreshold(4096); //
  fu.setRepositoryPath(temp); //

  int index = 0;
  List fileItems = null;

  try {
   fileItems = fu.parseRequest(request);
   System.out.println("fileItems=" + fileItems);
  } catch (Exception e) {
   e.printStackTrace();
  }

  Iterator iter = fileItems.iterator(); //
  while (iter.hasNext()) {
   FileItem item = (FileItem) iter.next();//
   if (!item.isFormField()) {
    String name = item.getName();//
    name = name.substring(name.lastIndexOf("\\") + 1);//
    long size = item.getSize();
    if ((name == null || name.equals("")) && size == 0)
     continue;
    int point = name.indexOf(".");
    name = (new Date()).getTime()
      + name.substring(point, name.length());//+ name.substring(point, name.length())+index
    index++;
    File fNew = new File(loadpath, name);
    try {
     item.write(fNew);
    } catch (Exception e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }

   } else//
   {
    String fieldvalue = item.getString();
    //
    // String fieldvalue = new
    // String(item.getString().getBytes(),"UTF-8");
   }
  }
  String text1 = "11";
  //response.sendRedirect("result.jsp?text1=" + text1);
 }

주의할점 :
add files in was and web project
commons-fileupload-1.3.jar
commons-io-2.4.jar

--------------------------------------------------------------------------------------------------------------------------

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

public class HttpFileUpTool {

 public static void post(String actionUrl, Map<String, String> params,
   Map<String, File> files) throws IOException {

  String BOUNDARY = java.util.UUID.randomUUID().toString();
  String PREFIX = "--", LINEND = "\r\n";
  String MULTIPART_FROM_DATA = "multipart/form-data";
  String CHARSET = "UTF-8";

  URL uri = new URL(actionUrl);
  HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
  conn.setReadTimeout(5 * 1000); //
  conn.setDoInput(true);//
  conn.setDoOutput(true);//
  conn.setUseCaches(false); //
  conn.setRequestMethod("POST");
  conn.setRequestProperty("connection", "keep-alive");
  conn.setRequestProperty("Charsert", "UTF-8");
  conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA
    + ";boundary=" + BOUNDARY);

  //
  StringBuilder sb = new StringBuilder();
  for (Map.Entry<String, String> entry : params.entrySet()) {
   sb.append(PREFIX);
   sb.append(BOUNDARY);
   sb.append(LINEND);
   sb.append("Content-Disposition: form-data; name=\""
     + entry.getKey() + "\"" + LINEND);
   sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND);
   sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
   sb.append(LINEND);
   sb.append(entry.getValue());
   sb.append(LINEND);
  }

  DataOutputStream outStream = new DataOutputStream(conn
    .getOutputStream());
  outStream.write(sb.toString().getBytes());
  InputStream in = null;
  //
  if (files != null){
   for (Map.Entry<String, File> file : files.entrySet()) {
    StringBuilder sb1 = new StringBuilder();
    sb1.append(PREFIX);
    sb1.append(BOUNDARY);
    sb1.append(LINEND);
    sb1
      .append("Content-Disposition: form-data; name=\"file\"; filename=\""
        + file.getKey() + "\"" + LINEND);
    sb1.append("Content-Type: application/octet-stream; charset="
      + CHARSET + LINEND);
    sb1.append(LINEND);
    outStream.write(sb1.toString().getBytes());

    InputStream is = new FileInputStream(file.getValue());
    byte[] buffer = new byte[1024];
    int len = 0;
    while ((len = is.read(buffer)) != -1) {
     outStream.write(buffer, 0, len);
    }

    is.close();
    outStream.write(LINEND.getBytes());
   }


  byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
  outStream.write(end_data);
  outStream.flush();

  int res = conn.getResponseCode();
  if (res == 200) {
   in = conn.getInputStream();
   int ch;
   StringBuilder sb2 = new StringBuilder();
   while ((ch = in.read()) != -1) {
    sb2.append((char) ch);
   }
  }
  outStream.close();
  conn.disconnect();
  }
//  return in.toString();
 }
}

    String actionUrl = "";
    Map<String, String> params = new HashMap<String, String>();
    params.put("title", "strParamValue");
    params.put("remark", "strParamValue");
    params.put("usemame", "strParamValue");
    params.put("usertel", "strParamValue");
    params.put("eventime", "strParamValue");
    params.put("evenaddress", "strParamValue");
    params.put("addtime", "strParamValue");
    params.put("edittime", "strParamValue");
    params.put("muploadid", "strParamValue");
    Map<String, File> files = new HashMap<String, File>();
    files.put("1.jpg", new File("/sdcard/1.jpg"));
    files.put("3.jpg", new File("/sdcard/3.jpg"));
    files.put("6.jpg", new File("/sdcard/6.jpg"));
    try {
      HttpFileUpTool.post(actionUrl, params, files);
     } catch (IOException e) {
      e.printStackTrace();
      Log.i(TAG, e.toString());
     }

추천 (0) 선물 (0명)
IP: ♡.101.♡.52
3,006 개의 글이 있습니다.
제목 글쓴이 날짜 조회
관리자
2003-09-20
11711
관리자
2003-09-20
11256
관리자
2003-09-20
20318
지구인
2010-08-27
19181
지구인
2009-09-07
13467
SOLIDH
2010-01-29
15461
엔죠라이프
2004-10-07
16569
CHOSUN
2014-01-11
2441
CHOSUN
2014-01-07
2596
CHOSUN
2014-01-07
2381
CHOSUN
2014-01-07
2050
CHOSUN
2014-01-07
1792
CHOSUN
2014-01-07
1612
CHOSUN
2014-01-07
1178
즐거운개굴
2013-09-29
3002
hmily1129
2013-09-03
4910
hmily1129
2013-08-29
5364
hmily1129
2013-08-26
4793
hmily1129
2013-08-25
3635
hmily1129
2013-08-24
4165
hmily1129
2013-08-23
4323
hmily1129
2013-08-23
3597
hmily1129
2013-08-22
1888
hmily1129
2013-08-10
1623
hmily1129
2013-08-05
2153
hmily1129
2013-08-05
2092
hmily1129
2013-07-30
1470
CHOSUN
2013-07-23
1942
모이자 모바일