2014-01-31 5 views
0

Привет Я работаю с андроидом. Я создал приложение для Android, которое загружает файл на сервер. Я использовал следующий кодAndroid не FileUpload работает

http://androidexample.com/Upload_File_To_Server_-_Android_Example/index.php?view=article_discription&aid=83&aaid=106

Но я не могу загрузить файл. Приложение показывает, загрузка началась, но файл не получает загружены в мое местоположение сервера.

ответ

0
 private class SendHttpRequestTask extends AsyncTask<String, Void, String> { 

     protected String doInBackground(String... params) { 

      String url = params[0]; 

      String param1 = params[1]; 

      String param2 = params[2]; 

     Bitmap b = BitmapFactory.decodeResource(UploadActivity.this.getResources(), R.drawable.logo); 



     ByteArrayOutputStream baos = new ByteArrayOutputStream(); 

     b.compress(CompressFormat.PNG, 0, baos); 



     try { 

      HttpClient client = new HttpClient(url); 

      client.connectForMultipart(); 

      client.addFormPart("param1", param1); 

      client.addFormPart("param2", param2); 

      client.addFilePart("file", "logo.png", baos.toByteArray()); 

      client.finishMultipart(); 

       String data = client.getResponse(); 

     } 

      catch(Throwable t) { 

      t.printStackTrace(); 

     } 



     return null; 

    } 



    @Override 

     protected void onPostExecute(String data) {   

     item.setActionView(null); 



     } 



    } 
0

общественный класс, кроме распространяется AsyncTask { личное MyProgressDialog pDialog;

@Override 
    protected void onPreExecute() { 
     pDialog = new MyProgressDialog(Send_message.this); 
     pDialog.setCancelable(false); 
     pDialog.show(); 
     super.onPreExecute(); 
    } 

    @Override 
    protected String doInBackground(String... paramss) { 
     try { 
      String json = messagesend.sendmeesage("Your Url",params); 
      JSONObject jsonobject = new JSONObject(json); 
      String result = jsonobject.getString("result"); 
      if (result.equals("TRUE")) { 
       return "true"; 
      } 

      System.out.println("json is" + json); 
     } catch (ClientProtocolException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 
     return "false"; 
    } 

    @Override 
    protected void onPostExecute(String result) { 
     super.onPostExecute(result); 
     pDialog.dismiss(); 
    } 

} 

// для отсылки файлов общественного класса messagesendwithhttp {

private String page; 

public String sendmeesage(String url, List<NameValuePair> nameValuePairs)throws ClientProtocolException, IOException 
{ 
    HttpClient httpClient = new DefaultHttpClient(); 
    HttpContext localContext = new BasicHttpContext(); 
    HttpPost httpPost = new HttpPost(url); 

    try { 
     MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); 

     for (int index = 0; index < nameValuePairs.size(); index++) 
     { 
      if (index == 0 || index == 1) 
      { 
       // If the key equals to "image", we use FileBody to transfer 
       // the data 
       entity.addPart(nameValuePairs.get(index).getName(), new StringBody(nameValuePairs.get(index).getValue())); 
      } else { 
       // Normal string data 
       if(nameValuePairs.get(index).getValue().equals("") || nameValuePairs.get(index).getValue().toString().equals(null)) 
       { 
        entity.addPart(
          nameValuePairs.get(index).getName(), 
          new StringBody(nameValuePairs.get(index).getValue())); 
       } 
       else 
       { 
        entity.addPart(nameValuePairs.get(index).getName(), 
         new FileBody(new File(nameValuePairs.get(index) 
           .getValue()))); 
       } 

      } 
     } 


     httpPost.setEntity(entity); 
     HttpResponse response = httpClient.execute(httpPost, localContext); 
     HttpEntity resEntity = response.getEntity(); 
     if (resEntity != null) 
     { 
      page = EntityUtils.toString(resEntity); 
      System.out.println("PAGE :" + page); 
     } 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
    return page; 
} 

}

enter code here 
+0

Я хочу, чтобы загрузить файл как текстовый файл, изображения, другие приложения к серверу БД, а не сообщения – doubter

0

вы можете использовать httpmime библиотеку, чтобы загрузить любой файл (изображение, аудио, видео и т.д ..) смотрите ниже код.

enter code here 


    HttpClient httpClient = new DefaultHttpClient(); 
    HttpContext localContext = new BasicHttpContext(); 
    HttpPost postRequest = new HttpPost(your url); 
    MultipartEntity reqEntity = new MultipartEntity(
      HttpMultipartMode.BROWSER_COMPATIBLE); 

    try { 




     File file = new File(filename); 
     FileBody fileBody = new FileBody(file); 
     reqEntity.addPart("video_file", fileBody); 

     postRequest.setEntity(reqEntity); 
     HttpResponse response = httpClient.execute(postRequest, 
       localContext); 
     HttpEntity entity = response.getEntity(); 

     if (entity != null) { 
      // entity.consumeContent(); 
      BufferedReader rd = new BufferedReader(new InputStreamReader(
        entity.getContent())); 
      // Log.e("response", "response " + rd.toString()); 
      String line; 
      String result1 = ""; 
      while ((line = rd.readLine()) != null) { 
       result1 = result1 + line; 
       // Log.e("result", "line " + line); 




    } 
      // Log.e("result", "is " + result1); 
      return result1; 
     } 
    } catch (Exception e) { 
     return "Exception"; 
    } 
    return ""; 
} 

}

+0

Пожалуйста, вы можете дать мне FuL образец кода ?? – doubter

0

Ее это падение окно ссылку на файл загружен в программу сервера https://www.dropbox.com/s/qasj5o5mu3dq5ya/file_remote_send.zip U Просто Изменить пыльник Код

адрес вашего сервера Место Здесь Струнный upLoadServerUri = «http://example.com/UploadToServer.php&#8221 ;;

здесь uploaded_file id php base filename conn.setRequestProperty ("uploaded_file", fileName);

UploadToServer.php

<?php 

$file_path = “uploads/”; 

$file_path = $file_path . basename($_FILES['uploaded_file']['name']); 
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path)) { 
echo “success”; 
} else{ 
echo “fail”; 
} 
?> 
+0

что uploaded_file ?? Есть ли какие-либо изменения, которые я хочу сделать в этом php-коде? – doubter

Смежные вопросы