PDA

View Full Version : ارسال فايل به سرور با كتابخانه volley



reza_web
سه شنبه 16 آذر 1395, 10:46 صبح
سلام
من با اين كتابخانه اطلاعات را به سرور ارسال مي كنم و مشكلي هم ندارد
حالا مي خواهم فايل هم ارسال كنم
اين آموزش را پيدا كردم:
https://www.simplifiedcoding.net/android-volley-tutorial-to-upload-image-to-server/
كه براي ارسال فايل تصويري به سرور مي باشد
ولي من مي خواهم هرنوع فايلي را ارسال كنم

در اين مثال يه تابعي به نام getStringImage وجود دارد كه ظاهرا فايل تصويري را به متن تبديل كرده و براي ارسال اماده مي كند. ولي من نميدانم چطوري براي ارسال هرنوع فايلي ازش استفاده كنم
ظاهرا بايد فايل به چيزي تبديل بشه جهت ارسال

كسي ميتونه منو راهنمايي كنه
ممنون

reza_web
چهارشنبه 17 آذر 1395, 13:19 عصر
تاحالا كسي فايل به سرور ارسال نكرده؟

reza_web
سه شنبه 30 آذر 1395, 08:36 صبح
حالا اگه كسي با اين كتابخانه كار نكرده راه حل ديگه اي بهم بده
واقعا كارم خيلي واجبه و گير كرده

hamedg1366
سه شنبه 30 آذر 1395, 09:04 صبح
سلام


لینک 1 (http://stackoverflow.com/questions/31700885/android-volley-library-how-to-send-an-image-to-server)

لینک 2 (http://stackoverflow.com/questions/32262829/how-to-upload-file-using-volley-library-in-android)

موفق باشی

reza_web
سه شنبه 30 آذر 1395, 10:17 صبح
دست شما درد نكنه
لطف كرديد
ولي پيدا كردن اين لينكها كار ساده اي است كه خيلي بيش از اينها خودم پيدا كردم
بالاخره همه ما گوگل بلديم

منظور من نمونه كد علمي بود نه رفع اشكال
اين سايت استك اورفلو پرسش و پاسخ و رفع اشكال است نه اموزشي
راستش من كه چيزي ازش نفهميدم(قطعا سواد من كافي نبوده)

اون لينكي كه خودم اون بالا دادم به طور كامل توضيح داده ولي متاسفانه فقط براي تصوير نه هر فايلي . منم نتونستم براي همه نوع فايل اصلاحش كنم

بهرحال بازم ممنون كه وقت گذاشتيد

1masoud1
جمعه 10 دی 1395, 00:55 صبح
سلام
برای ارسال هر نوع فایلی میشه اونو به آرایه بایتی تبدیل و بعد اونو به String تبدیل کرد و فرستاد سمت سرور این روش اگرچه جواب میده ولی منطقی نیست بهتره با استفاده از HttpUrlConnection استفاده کنی با این روش هر نوع فایلی رو میتونی همراه با متن به سرور بفرستی همچنین میتونی progressBar هم داشته باشی:

یه کلاس ایجاد کن به نام MultiPartUtility:



public class MultipartUtility {
private static final String LINE_FEED = "\r\n";
private final String boundary;
private final ProgressListener listener;
private HttpURLConnection httpConn;
private String charset;
private OutputStream outputStream;
private PrintWriter writer;




/**
* This constructor initializes a new HTTP POST request with content type
* is set to multipart/form-data
*
* @param requestURL
* @param charset
* @throws IOException
*/
public MultipartUtility(String requestURL, String charset, ProgressListener listener)
throws IOException {
this.charset = charset;
this.listener = listener;


// creates a unique boundary based on time stamp
boundary = "===" + System.currentTimeMillis() + "===";


URL url = new URL(requestURL);
httpConn = (HttpURLConnection) url.openConnection();
httpConn.setUseCaches(false);
httpConn.setDoOutput(true); // indicates POST method
httpConn.setDoInput(true);
httpConn.setRequestProperty("Content-Type",
"multipart/form-data; boundary=" + boundary);
// httpConn.setRequestProperty("User-Agent", "CodeJava Agent");
// httpConn.setRequestProperty("Test", "Bonjour");
outputStream = httpConn.getOutputStream();
writer = new PrintWriter(new OutputStreamWriter(outputStream, charset),
true);
}


/**
* Adds a form field to the request
*
* @param name field name
* @param value field value
*/
public void addFormField(String name, String value) {
writer.append("--" + boundary).append(LINE_FEED);
writer.append("Content-Disposition: form-data; name=\"" + name + "\"")
.append(LINE_FEED);
// writer.append("Content-Type: text/plain; charset=" + charset).append(
// LINE_FEED);
writer.append(LINE_FEED);
writer.append(value).append(LINE_FEED);
writer.flush();
}


/**
* Adds a upload file section to the request
*
* @param fieldName name attribute in <input type="file" name="..." />
* @param uploadFile a File to be uploaded
* @throws IOException
*/
public void addFilePart(String fieldName, File uploadFile)
throws IOException {
String fileName = uploadFile.getName();
writer.append("--" + boundary).append(LINE_FEED);
writer.append(
"Content-Disposition: form-data; name=\"" + fieldName
+ "\"; filename=\"" + fileName + "\"")
.append(LINE_FEED);
writer.append(
"Content-Type: "
+ URLConnection.guessContentTypeFromName(fileName))
.append(LINE_FEED);
writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
writer.append(LINE_FEED);
writer.flush();


FileInputStream inputStream = new FileInputStream(uploadFile);
byte[] buffer = new byte[4096];
int bytesRead = -1;


long totalRead = 0;
long totalSize = uploadFile.length();


while ((bytesRead = inputStream.read(buffer)) != -1) {


totalRead += bytesRead;
int percentage = (int) ((totalRead / (float) totalSize) * 100);


outputStream.write(buffer, 0, bytesRead);


if (listener != null) {


this.listener.transferred(percentage);
}
}
outputStream.flush();
inputStream.close();


writer.append(LINE_FEED);
writer.flush();
}


/**
* Adds a header field to the request.
*
* @param name - name of the header field
* @param value - value of the header field
*/
public void addHeaderField(String name, String value) {
writer.append(name + ": " + value).append(LINE_FEED);
writer.flush();
}


/**
* Completes the request and receives response from the server.
*
* @return a list of Strings as response in case the server returned
* status OK, otherwise an exception is thrown.
* @throws IOException
*/
public List<String> finish() throws IOException {
List<String> response = new ArrayList<String>();


writer.append(LINE_FEED).flush();
writer.append("--" + boundary + "--").append(LINE_FEED);
writer.close();


// checks server's status code first
int status = httpConn.getResponseCode();
if (status == HttpURLConnection.HTTP_OK) {
BufferedReader reader = new BufferedReader(new InputStreamReader(
httpConn.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
response.add(line);
}
reader.close();
httpConn.disconnect();
} else {
throw new IOException("Server returned non-OK status: " + status);
}


return response;
}


public interface ProgressListener {
void transferred(int num);
}


}


حالا یک AsyncTask ایجاد کن و داخل متد doInBackground :


MultipartUtility multipart = null;
try {
multipart = new MultipartUtility(urlServer, "UTF-8", new MultipartUtility.ProgressListener() {
@Override
public void transferred(int num) {
publishProgress(num);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
} catch (IOException e) {
e.printStackTrace();

// ba in code ha mitooni matn ersal koni
JsonObject json = new JsonObject();


json.put("key1" , "value1");
json.put("key2" , "value2");
json.put("key3" , "value3");


multipart.addFormField("YourKey", json.toString());




// ba in code mitooni file ersal koni
multipart.addFilePart(yourKey, file);

reza_web
یک شنبه 19 دی 1395, 13:24 عصر
سلام

من همه مراحل را رفتم و با اين دستورات هم فايل را به سرور ارسال مي كنم ولي خطا مي دهد


MultipartUtility multipart = null;
try {
multipart = new MultipartUtility("http://www.MYSITE.com/index.php?app/send_file", "UTF-8");
multipart.addFilePart("fileUpload", new File(uploadFile1.getPath()));


} catch (IOException e) {
e.printStackTrace();
}


اين هم خطا:

FATAL EXCEPTION: main
android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNe twork(StrictMode.java:1117)
at java.net.InetAddress.lookupHostByName(InetAddress. java:385)
at java.net.InetAddress.getAllByNameImpl(InetAddress. java:236)
at java.net.InetAddress.getAllByName(InetAddress.java :214)
at libcore.net.http.HttpConnection.<init>(HttpConnection.java:70)
at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50)
at libcore.net.http.HttpConnection$Address.connect(Ht tpConnection.java:340)
at libcore.net.http.HttpConnectionPool.get(HttpConnec tionPool.java:87)
at libcore.net.http.HttpConnection.connect(HttpConnec tion.java:128)
at libcore.net.http.HttpEngine.openSocketConnection(H ttpEngine.java:316)
at libcore.net.http.HttpEngine.connect(HttpEngine.jav a:311)
at libcore.net.http.HttpEngine.sendSocketRequest(Http Engine.java:290)
at libcore.net.http.HttpEngine.sendRequest(HttpEngine .java:240)
at libcore.net.http.HttpURLConnectionImpl.connect(Htt pURLConnectionImpl.java:81)
at libcore.net.http.HttpURLConnectionImpl.getOutputSt ream(HttpURLConnectionImpl.java:197)
at ghazalina.sytama.MultipartUtility.<init>(MultipartUtility.java:55)
at ghazalina.sytama.Evaluation$1$2.onClick(Evaluation .java:318)
at com.android.internal.app.AlertController$ButtonHan dler.handleMessage(AlertController.java:166)
at android.os.Handler.dispatchMessage(Handler.java:99 )
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.jav a:5041)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCa ller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit .java:560)
at dalvik.system.NativeStart.main(Native Method)


نميدونم كد سمت سرور مشكل داره يا اين كدي كه نوشته ام

كد بخش سرور



function send_file(){

$allowed = array('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'text/plain','application/pdf','image/jpeg','image/gif','image/tiff','application/msword',
'text/html','image/png','application/msword','application/vnd.openxmlformats-officedocument.wordprocessingml.document');
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $_FILES['fileUpload']['tmp_name']);
$size = filesize($_FILES['fileUpload']['tmp_name']);
finfo_close($finfo);
if((in_array($mime,$allowed) && $size<500000 && $_FILES['fileUpload']['tmp_name'] != "") || $_FILES['fileUpload']['tmp_name'] == "" ) {
if($_FILES['fileUpload']['tmp_name'] != ""){
$type = explode(".",$_FILES['fileUpload']['name']);
$filename = 'uploads/pp'.rand(111111111, 999999999).'.'.$type[1];
move_uploaded_file($_FILES['fileUpload']['tmp_name'], $filename);
}
}
}

spiderman200700
یک شنبه 19 دی 1395, 17:04 عصر
برای سادگی کار بهتره از کتابخونه VolleyPlus استفاده کنی.
برای استفاده اول این خط رو در فایل build.gradle قرار بدید.

compile 'dev.dworks.libs:volleyplus:+'



بعد با این کد همزمان میتونید هم فایل هم متن ارسال کنید:

String url = "http://host.domain";
MultiPartRequest request = new SimpleMultiPartRequest(Request.Method.POST, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.i("onResponse", response.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.i("onErrorResponse", error.toString());
}
});
File file = new File("file path");
request.addFile("fileName", file.getAbsolutePath());

String params = "some parameters";
request.addStringParam("params", params);

MyApplication.getInstance().addToRequestQueue(requ est);

reza_web
دوشنبه 20 دی 1395, 10:27 صبح
دست شما درد نكنه
ولي متاسفانه نميشه اين كتابخانه را به برنامه اضافه كنم
ظاهرا علتش اينه كه ما از MavenCentral استفاده مي كنيم (به علت تحريم) و اين كتابخانه از jcenter

نميشه كاريش كرد؟

محمد رضا فاتحی
دوشنبه 20 دی 1395, 12:11 عصر
برای سادگی کار بهتره از کتابخونه VolleyPlus استفاده کنی.
برای استفاده اول این خط رو در فایل build.gradle قرار بدید.
compile 'dev.dworks.libs:volleyplus:+'


بعد با این کد همزمان میتونید هم فایل هم متن ارسال کنید:
String url = "http://host.domain";
MultiPartRequest request = new SimpleMultiPartRequest(Request.Method.POST, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.i("onResponse", response.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.i("onErrorResponse", error.toString());
}
});
File file = new File("file path");
request.addFile("fileName", file.getAbsolutePath());

String params = "some parameters";
request.addStringParam("params", params);

MyApplication.getInstance().addToRequestQueue(requ est);
MyApplication از چه نوعیه؟

1masoud1
دوشنبه 20 دی 1395, 13:21 عصر
سلام

من همه مراحل را رفتم و با اين دستورات هم فايل را به سرور ارسال مي كنم ولي خطا مي دهد


MultipartUtility multipart = null;
try {
multipart = new MultipartUtility("http://www.MYSITE.com/index.php?app/send_file", "UTF-8");
multipart.addFilePart("fileUpload", new File(uploadFile1.getPath()));


} catch (IOException e) {
e.printStackTrace();
}


اين هم خطا:

FATAL EXCEPTION: main
android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNe twork(StrictMode.java:1117)
at java.net.InetAddress.lookupHostByName(InetAddress. java:385)
at java.net.InetAddress.getAllByNameImpl(InetAddress. java:236)
at java.net.InetAddress.getAllByName(InetAddress.java :214)
at libcore.net.http.HttpConnection.<init>(HttpConnection.java:70)
at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50)
at libcore.net.http.HttpConnection$Address.connect(Ht tpConnection.java:340)
at libcore.net.http.HttpConnectionPool.get(HttpConnec tionPool.java:87)
at libcore.net.http.HttpConnection.connect(HttpConnec tion.java:128)
at libcore.net.http.HttpEngine.openSocketConnection(H ttpEngine.java:316)
at libcore.net.http.HttpEngine.connect(HttpEngine.jav a:311)
at libcore.net.http.HttpEngine.sendSocketRequest(Http Engine.java:290)
at libcore.net.http.HttpEngine.sendRequest(HttpEngine .java:240)
at libcore.net.http.HttpURLConnectionImpl.connect(Htt pURLConnectionImpl.java:81)
at libcore.net.http.HttpURLConnectionImpl.getOutputSt ream(HttpURLConnectionImpl.java:197)
at ghazalina.sytama.MultipartUtility.<init>(MultipartUtility.java:55)
at ghazalina.sytama.Evaluation$1$2.onClick(Evaluation .java:318)
at com.android.internal.app.AlertController$ButtonHan dler.handleMessage(AlertController.java:166)
at android.os.Handler.dispatchMessage(Handler.java:99 )
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.jav a:5041)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCa ller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit .java:560)
at dalvik.system.NativeStart.main(Native Method)


نميدونم كد سمت سرور مشكل داره يا اين كدي كه نوشته ام

كد بخش سرور



function send_file(){

$allowed = array('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'text/plain','application/pdf','image/jpeg','image/gif','image/tiff','application/msword',
'text/html','image/png','application/msword','application/vnd.openxmlformats-officedocument.wordprocessingml.document');
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $_FILES['fileUpload']['tmp_name']);
$size = filesize($_FILES['fileUpload']['tmp_name']);
finfo_close($finfo);
if((in_array($mime,$allowed) && $size<500000 && $_FILES['fileUpload']['tmp_name'] != "") || $_FILES['fileUpload']['tmp_name'] == "" ) {
if($_FILES['fileUpload']['tmp_name'] != ""){
$type = explode(".",$_FILES['fileUpload']['name']);
$filename = 'uploads/pp'.rand(111111111, 999999999).'.'.$type[1];
move_uploaded_file($_FILES['fileUpload']['tmp_name'], $filename);
}
}
}



این خطا وقتی اتفاق میوفته که ارتباط با سرور رو در ترد اصلی برنامه اجرا بشه برای ارسال فایل به سرور باید از Asynctask یا ترد استفاده کنین تا ارتباط با سرور به صورت موازی با برنامه انجام بشه و ترد اصلی برنامه درگیر ارتباط با سرور نشه

spiderman200700
دوشنبه 20 دی 1395, 15:11 عصر
MyApplication از چه نوعیه؟

از نوع android.app.Application
باید توی کلاس MyApplication متد های مربوط به ارسال درخواست توسط Volley رو نوشته باشید.
اگر نیاز بود دوستان بگن تا کلاس MyApplication رو هم قرار بدم

محمد رضا فاتحی
چهارشنبه 22 دی 1395, 12:01 عصر
از نوع android.app.Application
باید توی کلاس MyApplication متد های مربوط به ارسال درخواست توسط Volley رو نوشته باشید.
اگر نیاز بود دوستان بگن تا کلاس MyApplication رو هم قرار بدم

اگه زحمتش روبکشید که ممنون میشیم...یااگه نمونه سورسی دارید:افسرده:

spiderman200700
چهارشنبه 22 دی 1395, 14:50 عصر
کلاس MyApplication:

public class MyApplication extends Application {


private static MyApplication mInstance;
private RequestQueue mRequestQueue;
public static OkHttpClient client;

@Override
public void onCreate() {
super.onCreate();
mInstance = this;
initOKHTTPClient(this);
}


private static final Interceptor REWRITE_CACHE_CONTROL_INTERCEPTOR = new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
okhttp3.Request originalRequest = chain.request();
String cacheHeaderValue = isOnline() ? "public, max-age=2419200"
: "public, only-if-cached, max-stale=2419200";

okhttp3.Request request = originalRequest.newBuilder().build();
Response response = chain.proceed(request);
return response.newBuilder().removeHeader("Pragma")
.removeHeader("Cache-Control")
.header("Cache-Control", cacheHeaderValue).build();

}
};

public static void initOKHTTPClient(Context context) {
Log.i("ExternalCacheDir", context.getExternalCacheDir() + "");
Cache cache = new Cache(context.getExternalCacheDir(), 1024 * 1024 * 30);

client = new OkHttpClient.Builder().retryOnConnectionFailure(tr ue)
.connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(10, TimeUnit.SECONDS)
.addNetworkInterceptor(REWRITE_CACHE_CONTROL_INTER CEPTOR)
.addInterceptor(REWRITE_CACHE_CONTROL_INTERCEPTOR)
// .addNetworkInterceptor(RETRY_INTERCEPTOR)
// .addInterceptor(RETRY_INTERCEPTOR)
.cache(cache).build();

}

public static boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) mInstance.getSystemService(Context.CONNECTIVITY_SE RVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return netInfo != null && netInfo.isConnectedOrConnecting();
}

public static synchronized MyApplication getInstance() {
return mInstance;
}

public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext(),
new OkHttpStack(client));
}
return mRequestQueue;
}


public <T> void addToRequestQueue(Request<T> req) {
getRequestQueue().add(req);
}

public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}

}





کلاس OkHttpStack:
public class OkHttpStack implements HttpStack {

private final OkHttpClient mClient;

public OkHttpStack(OkHttpClient client) {
this.mClient = client;
}

@Override
public HttpResponse performRequest(Request<?> request,
Map<String, String> additionalHeaders) throws IOException,
AuthFailureError {

okhttp3.Request.Builder okHttpRequestBuilder = new okhttp3.Request.Builder();
okHttpRequestBuilder.url(request.getUrl());

Map<String, String> headers = request.getHeaders();
for (final String name : headers.keySet()) {
okHttpRequestBuilder.addHeader(name, headers.get(name));
}
for (final String name : additionalHeaders.keySet()) {
okHttpRequestBuilder.addHeader(name, additionalHeaders.get(name));
}

setConnectionParametersForRequest(okHttpRequestBui lder, request);

okhttp3.Request okHttpRequest = okHttpRequestBuilder.build();
Call okHttpCall = mClient.newCall(okHttpRequest);
Response okHttpResponse = okHttpCall.execute();

StatusLine responseStatus = new BasicStatusLine(
parseProtocol(okHttpResponse.protocol()),
okHttpResponse.code(), okHttpResponse.message());
BasicHttpResponse response = new BasicHttpResponse(responseStatus);
response.setEntity(entityFromOkHttpResponse(okHttp Response));

Headers responseHeaders = okHttpResponse.headers();
for (int i = 0, len = responseHeaders.size(); i < len; i++) {
final String name = responseHeaders.name(i), value = responseHeaders
.value(i);
if (name != null) {
response.addHeader(new BasicHeader(name, value));
}
}

return response;
}

private static HttpEntity entityFromOkHttpResponse(Response r)
throws IOException {
BasicHttpEntity entity = new BasicHttpEntity();
ResponseBody body = r.body();

entity.setContent(body.byteStream());
entity.setContentLength(body.contentLength());
entity.setContentEncoding(r.header("Content-Encoding"));

if (body.contentType() != null) {
entity.setContentType(body.contentType().type());
}
return entity;
}

@SuppressWarnings("deprecation")
private static void setConnectionParametersForRequest(
okhttp3.Request.Builder builder, Request<?> request)
throws IOException, AuthFailureError {
switch (request.getMethod()) {
case Request.Method.DEPRECATED_GET_OR_POST:
// Ensure backwards compatibility. Volley assumes a request with a
// null body is a GET.
byte[] postBody = request.getPostBody();
if (postBody != null) {
builder.post(RequestBody.create(
MediaType.parse(request.getPostBodyContentType()),
postBody));
}
break;
case Request.Method.GET:
builder.get();
break;
case Request.Method.DELETE:
builder.delete();
break;
case Request.Method.POST:
builder.post(createRequestBody(request));
break;
case Request.Method.PUT:
builder.put(createRequestBody(request));
break;
case Request.Method.HEAD:
builder.head();
break;
case Request.Method.OPTIONS:
builder.method("OPTIONS", null);
break;
case Request.Method.TRACE:
builder.method("TRACE", null);
break;
case Request.Method.PATCH:
builder.patch(createRequestBody(request));
break;
default:
throw new IllegalStateException("Unknown method type.");
}
}

private static ProtocolVersion parseProtocol(final Protocol p) {
switch (p) {
case HTTP_1_0:
return new ProtocolVersion("HTTP", 1, 0);
case HTTP_1_1:
return new ProtocolVersion("HTTP", 1, 1);
case SPDY_3:
return new ProtocolVersion("SPDY", 3, 1);
case HTTP_2:
return new ProtocolVersion("HTTP", 2, 0);
}

throw new IllegalAccessError("Unkwown protocol");
}

private static RequestBody createRequestBody(Request r)
throws AuthFailureError {
if (r instanceof JsonRequest || r instanceof StringRequest) {
final byte[] body = r.getBody();
if (body == null)
return null;

return RequestBody
.create(MediaType.parse(r.getBodyContentType()), body);
} else if (r instanceof MultiPartRequest) {
MultiPartRequest mlpRequest = (MultiPartRequest) r;
MultipartBody.Builder builder = new MultipartBody.Builder();
builder.setType(MultipartBody.FORM);

if (mlpRequest.getMultipartParams() != null && !mlpRequest.getMultipartParams().isEmpty()) {
for (Object key : mlpRequest.getMultipartParams().keySet()) {
MultiPartRequest.MultiPartParam p = (MultiPartRequest.MultiPartParam) mlpRequest.getMultipartParams().get(key);
Log.w("param", key + ":" + p.value);
builder.addFormDataPart(key.toString(), p.value);
}
}

if (mlpRequest.getFilesToUpload() != null && !mlpRequest.getFilesToUpload().isEmpty()) {
final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
for (Object key :
mlpRequest.getFilesToUpload().keySet()) {
Log.w("fileParam", key + ":" + mlpRequest.getFilesToUpload().get(key).toString()) ;

File file = new File(mlpRequest.getFilesToUpload().get(key).toStri ng());
builder.addFormDataPart(key.toString(), file.getName(),
RequestBody.create(MEDIA_TYPE_PNG, file));
}
}
return builder.build();
}
return null;
}

}




توی فایل Build.gradle در بلاک android هم این خط رو قرار بدید:
useLibrary 'org.apache.http.legacy'


توی فایل Build.gradle در بلاک dependencies این خط رو قرار بدید:
compile 'dev.dworks.libs:volleyplus:+'
compile 'com.squareup.okhttp3:okhttp:3.4.1'




برای جامع شدن پست نحوه استفاده رو بازم اینجا توضیح میدم.
با این کد همزمان میتونید هم فایل هم متن ارسال کنید:






String url = "http://host.domain";

MultiPartRequest request = new SimpleMultiPartRequest(Request.Method.POST, url, new Response.Listener<String>() {

@Override

public void onResponse(String response) {

Log.i("onResponse", response.toString());

}

}, new Response.ErrorListener() {

@Override

public void onErrorResponse(VolleyError error) {

Log.i("onErrorResponse", error.toString());

}

});

File file = new File("file path");

request.addFile("fileName", file.getAbsolutePath());



String params = "some parameters";

request.addStringParam("params", params);



MyApplication.getInstance().addToRequestQueue(requ est);