2016-09-29 70 views
1

我如何使用排球庫從移動設備發送文件(數據)到服務器。如何在android中將文件上傳到服務器?

這裏我列出了我的參數,請幫我解決這個問題。

 Map<String, String> mHeaderPart= new HashMap<>(); 
      mHeaderPart.put("Content-type", "multipart/form-data;"); 
      mHeaderPart.put("Authorization", authorizationKey); 


    //String part 
      Map<String, String> mStringPart= new HashMap<>(); 
      mStringPart.put("candidate_id", SessionStores.getBullHornId(getActivity())); 
      mStringPart.put("externalID", "portpolio"); 
      mStringPart.put("fileCount", "2");//number of files 
      mStringPart.put("fileType", "SAMPLE"); 
      mStringPart.put("platform", "android"); 

//file param 

    Map<String, File> mFilePartData= new HashMap<>(); 

在上面的文件參數中,我必須添加n個文件並將其發送到服務器。我如何從設備獲取文件,並添加n個文件與param並將其發送到服務器,如果有人可以請給我建議。

如果有人有使用抽球發送多個文件與param的例子,請指導我。提前致謝。

+0

可能重複[如何使用Volley庫上傳圖像?](http://stackoverflow.com/questions/27112694/how-to-do-upload-image -with-volley-library) – Nitesh

+0

結帳例如[Stackoverflow Link](http:// stackoverfl ow.com/questions/16797468/how-to-send-a-multipart-form-data-post-in-android-with-volley)(http://stackoverflow.com/questions/32262829/how -to-upload-file-using-volley-library-in-android) – mpals

+0

感謝您的回覆@Nitesh,mplas。我懷疑如何發送filecontent參數作爲一個數組發送多個文件。像filecontent0,filecontent1 /這裏filecontent是文件參數添加文件。 – karthik

回答

0

Volly不提供使用多部分在服務器上上傳文件的直接方式。

用於上傳使用volly按如下步驟多個文件:

步驟1:創建一個名爲MultipartRequest.java新類從volly像下方延伸請求:

import com.android.volley.AuthFailureError; 

import com.android.volley.NetworkResponse; 

import com.android.volley.ParseError; 

import com.android.volley.Request; 

import com.android.volley.Response; 

import com.android.volley.VolleyLog; 

import com.android.volley.toolbox.HttpHeaderParser; 

import org.apache.http.HttpEntity; 

import org.apache.http.entity.mime.MultipartEntityBuilder; 

import org.apache.http.entity.mime.content.FileBody; 

import java.io.ByteArrayOutputStream; 

import java.io.File; 

import java.io.IOException; 

import java.io.UnsupportedEncodingException; 

import java.util.HashMap; 

import java.util.Map; 

public class MultipartRequest extends Request<String> { private MultipartEntityBuilder entitybuilder = MultipartEntityBuilder.create(); HttpEntity entity; 

    private HashMap<String, File> sendFile = new HashMap<>(); 

    /** 
    * 
    * @param url    url 
    * @param errorListener  volly error listenere 
    * @param sendFile   HashMap with key as file name and value as file object 
    */ 

    public MultipartRequest(String url, Response.ErrorListener errorListener, HashMap<String, File> sendFile) { 
    super(Method.POST, url, errorListener); 

    this.sendFile = sendFile; 
    buildMultipartEntity(); 
    entity = entitybuilder.build(); 
    } 

    private void buildMultipartEntity() { 

    if (sendFile != null) 
     for (Map.Entry<String, File> entry : sendFile.entrySet()) { 
      entitybuilder.addPart(entry.getKey(), new FileBody(entry.getValue())); 

      // here you can set key as filename 
      // value will be the file object to be upload 

     } 
    } 

    @Override 
    public String getBodyContentType() { 
    return entity.getContentType().getValue(); 
    } 

    @Override 
    public byte[] getBody() throws AuthFailureError { 
    ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
    try { 
     entity.writeTo(bos); 
    } catch (IOException e) { 
     VolleyLog.e("IOException writing to ByteArrayOutputStream"); 
    } 
    return bos.toByteArray(); 
    } 

    @Override 
    protected Response<String> parseNetworkResponse(NetworkResponse networkResponse) { 
    try { 
     String json = new String(
       networkResponse.data, HttpHeaderParser.parseCharset(networkResponse.headers)); 
     return Response.success(json, HttpHeaderParser.parseCacheHeaders(networkResponse)); 

    } catch (UnsupportedEncodingException e) { 
     return Response.error(new ParseError(e)); 
    } 
    } 

    @Override 
    protected void deliverResponse(String s) { 

    //Your response 

    } 
} 

步驟2:

來自你的活動:

public void executeMultipart(String url,HashMap<String, File> fileData) { 
    try { MultipartRequest mRequest = new MultipartRequest(url , new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError volleyError) { 

      } 
     },fileData); 
     mRequest.setRetryPolicy(new DefaultRetryPolicy(
       (int) TimeUnit.SECONDS.toMillis(20), 
       DefaultRetryPolicy.DEFAULT_MAX_RETRIES, 
       DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
    } 

第3步:在你的應用的build.gradle文件中加入:

compile('org.apache.httpcomponents:httpmime:4.3.6') { exclude module: 'httpclient' } 

注意:從API 22 org.apache.http.HttpEntity被棄用,因此,更好地爲使用的URLConnection或者你可以使用改造庫都有自己的優點和缺點

相關問題