Android multipart file upload with OkHttp - java

I am using this for audio records and video file and it is working but i want to replace it with OkHttp. I didnt figure it out. Can anyone help me about it?
public class HttpMultipartUpload {
static String lineEnd = "\r\n";
static String twoHyphens = "--";
static String boundary = "AaB03x87yxdkjnxvi7";
public static String upload(URL url, File file, String fileParameterName, HashMap<String, String> parameters)
throws IOException {
HttpURLConnection conn = null;
DataOutputStream dos = null;
DataInputStream dis = null;
FileInputStream fileInputStream = null;
byte[] buffer;
int maxBufferSize = 20 * 1024;
try {
//------------------ CLIENT REQUEST
fileInputStream = new FileInputStream(file);
// open a URL connection to the Servlet
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
// Allow Inputs
conn.setDoInput(true);
// Allow Outputs
conn.setDoOutput(true);
// Don't use a cached copy.
conn.setUseCaches(false);
// Use a post method.
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"" + fileParameterName
+ "\"; filename=\"" + file.toString() + "\"" + lineEnd);
dos.writeBytes("Content-Type: text/xml" + lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
buffer = new byte[Math.min((int) file.length(), maxBufferSize)];
int length;
// read file and write it into form...
while ((length = fileInputStream.read(buffer)) != -1) {
dos.write(buffer, 0, length);
}
for (String name : parameters.keySet()) {
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"" + name + "\"" + lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(parameters.get(name));
}
// send multipart form data necessary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
dos.flush();
} finally {
if (fileInputStream != null) fileInputStream.close();
if (dos != null) dos.close();
}
//------------------ read the SERVER RESPONSE
try {
dis = new DataInputStream(conn.getInputStream());
StringBuilder response = new StringBuilder();
String line;
while ((line = dis.readLine()) != null) {
response.append(line).append('\n');
}
return response.toString();
} finally {
if (dis != null) dis.close();
}
}
}
How can I change it with OkHttp. Any code please. I dont have good knowledge about on OkHttp. I was using (HttpURLConnection) but it seems not effective now.

See the documentation example on posting form data
https://github.com/square/okhttp/blob/master/samples/guide/src/main/java/okhttp3/recipes/PostMultipart.java
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("title", "Square Logo")
.addFormDataPart("image", "logo-square.png",
RequestBody.create(
new File("docs/images/logo-square.png"),
MEDIA_TYPE_PNG))
.build();
Request request = new Request.Builder()
.header("Authorization", "Client-ID " + IMGUR_CLIENT_ID)
.url("https://api.imgur.com/3/image")
.post(requestBody)
.build();

Related

An illegal attempt was made to upload a document

Response:400 - {"error":"An illegal attempt was made to upload a document"}
Getting the above error while uploading a file through HttpURLconnection Java. Tried all the methods for converting file to bytearray > byte[] bytes = Files.readAllBytes(file.toPath());
and > byte[] bytes = FileUtils.readFileToByteArray(file);
Can anyone help me to fix the code?
public static Response upload(HttpURLConnection connection, String request, String filePath) throws IOException, InterruptedException
{
String response = "";
Integer code = -1;
String boundary = "*****";
String crlf = "\r\n";
String twoHyphens = "--";
String type = "144";
String parentID = "601903197";
connection.setUseCaches(false);
connection.setDoOutput(true); /* indicates POST method */
connection.setDoInput(true);
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Cache-Control", "no-cache");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
File file = new File(filePath);
String fileBaseName = FilenameUtils.getBaseName(file.toString());
request = request.trim();
if (request != "") {
try (DataOutputStream dos = new DataOutputStream(connection.getOutputStream())) {
dos.writeBytes(twoHyphens + boundary + crlf);
dos.writeBytes("Content-Disposition: form-data; name=\"parent_id\""+crlf);
dos.writeBytes("Content-Type: text/plain; charset=utf-8"+crlf);
dos.writeBytes(crlf);
dos.writeBytes(parentID+crlf);
dos.flush();
dos.writeBytes(twoHyphens + boundary + crlf);
dos.writeBytes("Content-Disposition: form-data; name=\"type\""+crlf);
dos.writeBytes("Content-Type: text/plain; charset=utf-8"+crlf);
dos.writeBytes(crlf);
dos.writeBytes(type+crlf);
dos.flush();
dos.writeBytes(twoHyphens + boundary + crlf);
dos.writeBytes("Content-Disposition: form-data; name=\"name\""+crlf);
dos.writeBytes("Content-Type: text/plain; charset=utf-8"+crlf);
dos.writeBytes(crlf);
dos.writeBytes(fileBaseName+crlf);
dos.flush();
dos.writeBytes(twoHyphens + boundary + crlf);
dos.writeBytes("Content-Disposition: form-data; name=\"file\";filename\""+file.getName()+"\""+crlf);
String mimetype = connection.guessContentTypeFromName(file.getName());
mimetype = mimetype == null ? "application/octet-stream" : mimetype;
dos.writeBytes("Content-Type: " + mimetype + crlf);
dos.writeBytes("Content-Transfer-Encoding: binary"+crlf);
dos.writeBytes(crlf);
FileInputStream inputStream = new FileInputStream(file);
byte[] bytes = new byte[4096];
int bytesRead = -1;
while ((bytesRead = inputStream.read(bytes)) != -1) {
dos.write(bytes, 0, bytesRead);
}
inputStream.close();
dos.writeBytes(crlf);
dos.writeBytes(twoHyphens + boundary + twoHyphens + crlf);
dos.flush();
}
}
code = connection.getResponseCode();
var errorStream = connection.getErrorStream();
InputStream stream = errorStream != null ? errorStream : connection.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(stream));
String inputLine;
StringBuffer responseBuffer = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
responseBuffer.append(inputLine);
}
in.close();
connection.disconnect();
response = responseBuffer.toString();
return new Response(code, response);
}

Unable to upload a file to server in android?

I have a problem with uploading file to the server. Here i'm trying to create the registration form.
I need to upload all values that taken from user, along with that i need to upload the resume resume is in PDF format.
Here is my code. Please look into it.
public String serverResponse(String mFilePath){
HttpClient client = new DefaultHttpClient();
HttpPost poster = new HttpPost(mUrl);
File resume = new File(mFilePath); //Actual file from the device
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("name", new StringBody("name"));
entity.addPart("phone", new StringBody("1234567890"));
entity.addPart("attachment", new FileBody(resume));
poster.setEntity(entity);
return client.execute(poster, new ResponseHandler<String>() {
public String handleResponse(HttpResponse response) throws IOException {
HttpEntity respEntity = response.getEntity();
return EntityUtils.toString(respEntity);
}
});
}
The problem is above code works when i send the data to url("http://www.example.com"), and it doesn't works on the url("https://www.example.com").
can anyone tell what's wrong on my code.
Please help me on this.
Edit : I checked the request from android in server side, there i found empty data in request and it response back with default message(response that set in server).
so my request hits the server with empty values. Is problem in my code (or) server side ?
just now i checked, that this same URL works fine in website.
Please direct me in correct way if i was wrong
Thanks in Advance.
try this code i hope this will help you.
public String uploadFile(String filePath, String name, String phone, String url) throws Exception {
String crlf = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
HttpURLConnection httpUrlConnection = null;
OutputStream outputStream = null;
InputStream inputStream = null;
InputStreamReader in = null;
try {
URL urlObj = new URL(url);
httpUrlConnection = (HttpURLConnection) urlObj.openConnection();
httpUrlConnection.setReadTimeout(10 * 1000);
httpUrlConnection.setConnectTimeout(10 * 1000);
httpUrlConnection.setDoInput(true);
File file = new File(filePath);
if (file != null) {
httpUrlConnection.setUseCaches(false);
httpUrlConnection.setRequestMethod("POST");
httpUrlConnection.setRequestProperty("Connection", "Keep-Alive");
httpUrlConnection.setRequestProperty("Cache-Control", "no-cache");
httpUrlConnection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
outputStream = httpUrlConnection.getOutputStream();
outputStream.write((crlf + twoHyphens + boundary + crlf).getBytes());
outputStream.write(("Content-Disposition: form-data; name=\"name\"" + crlf + crlf + name).getBytes());
outputStream.write((crlf + twoHyphens + boundary + crlf).getBytes());
outputStream.write(("Content-Disposition: form-data; name=\"phone\"" + crlf + crlf + phone).getBytes());
outputStream.write((crlf + twoHyphens + boundary + crlf).getBytes());
Log.e("Response :", "Response Code : " + file.getName());
outputStream.write(("Content-Disposition: form-data; name=\"file\"; filename=\""
+ file.getName()
+ "\""
+ crlf
+ "Content-Type: image/jpeg" + crlf).getBytes());
outputStream.write(crlf.getBytes());
FileInputStream fis = new FileInputStream(file);
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
outputStream.write(crlf.getBytes());
outputStream.write((twoHyphens + boundary + twoHyphens + crlf).getBytes());
outputStream.flush();
outputStream.close();
fis.close();
}
httpUrlConnection.connect();
Log.e("Response :", "Response Code : " + httpUrlConnection.getResponseCode());
if (httpUrlConnection.getResponseCode() == -1) {
onImageUploadCompleted.onImageUploadCompleted("error -1");
Log.e("Connection error", "Connection error: url " + url);
String json = "{\"error\": {\"code\": 991, \"message\": \"Connection error: `991`\"}}";
}
if (httpUrlConnection.getResponseCode() == 204) {
return "Upload failed";
}
if (httpUrlConnection.getResponseCode() == 200) {
inputStream = httpUrlConnection.getInputStream();
}
else
inputStream = httpUrlConnection.getErrorStream();
in = new InputStreamReader(inputStream);
StringBuilder sb = new StringBuilder();
int read;
char[] buff = new char[1024];
while ((read = in.read(buff)) != -1) {
sb.append(buff, 0, read);
}
File f = new File(filePath);
f.delete();
Log.e("Response ", "Response text : " + sb.toString());
if (httpUrlConnection.getResponseCode() != 200) {
//ParseJson.parseException(sb.toString());
Log.e("Failed", "Failed safe : " + sb.toString());
return sb.toString();
}
return sb.toString();
} catch (Exception e) {
if (outputStream != null) {
outputStream.close();
}
if (in != null) {
in.close();
}
if (inputStream != null) {
inputStream.close();
}
e.printStackTrace();
} finally {
if (httpUrlConnection != null) {
httpUrlConnection.disconnect();
}
}
return null;
}
I use this code to post a file.Should be used in background thread, and function will return the server response.
public String postFile(String mFileName,String apiUrl,String fileType,HashMap<String,String> params) throws Exception{
String output = "null";
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
InputStream inputStream = null;
String twoHyphens = "--";
String boundary = "*****" + Long.toString(System.currentTimeMillis())
+ "*****";
String lineEnd = "\r\n";
String result = "";
int bytesRead, bytesAvailable, bufferSize, bytesTransffered, bytesTotals;
byte[] buffer;
int maxBufferSize = 10;
String[] q = mFileName.split("/");
int idx = q.length - 1;
File file = new File(mFileName);
FileInputStream fileInputStream = new FileInputStream(file);
URL url = new URL(apiUrl);
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("User-Agent",
"Android Multipart HTTP Client 1.0");
connection.setRequestProperty("Content-Type",
"multipart/form-data; boundary=" + boundary);
outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
Log.d(TAG, "msg is " + q[idx]);
outputStream.writeBytes("Content-Disposition: form-data; name=\""
+ "file" + "\"; filename=\"" + q[idx] + "\"" + lineEnd);
outputStream.writeBytes("Content-Type: " + fileType + lineEnd);
outputStream.writeBytes("Content-Transfer-Encoding: binary"
+ lineEnd);
outputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
long bytesTotal = file.length();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
bytesTransffered = 0;
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
bytesTransffered = bytesRead;
while (bytesRead > 0) {
outputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
bytesTransffered += bytesRead;
if (mProgressUpdateListener != null) {
publishProgress((100 * bytesTransffered)
/ Integer.parseInt(bytesTotal + ""));
} else {
Log.d(TAG, "Progress Listener is Null");
}
}
outputStream.writeBytes(lineEnd);
Iterator it = params.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
String key= (String) pair.getKey();
String value = (String) pair.getValue();
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"" + key + "\"" + lineEnd);
outputStream.writeBytes("Content-Type: text/plain" + lineEnd);
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(value);
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens
+ lineEnd);
}
Log.d(TAG,"Response code "+connection.getResponseCode());
if (connection.getResponseCode() == 200) {
InputStream in = connection.getInputStream();
BufferedReader rd = new BufferedReader(
new InputStreamReader(in));
output = "";
String line;
while ((line = rd.readLine()) != null) {
output += line;
}
}
return output;
}
Use Retrofit to uplaod a file.
It is faster and easy
Create an interface
public interface ApiClient {
#Multipart
#POST(NetworkUtils.UPLOAD_PHOTO_URL)
Call<PhotoResponseModel> uploadPhoto(
#Header("id") String id,
#Header("imageId") String imageId,
/*#Part("description") RequestBody description,*/
#Part MultipartBody.Part photo);
}
call this method
public void syncPhoto()
{
Retrofit.Builder builder = new Retrofit.Builder()
.baseUrl(NetworkUtils.SERVER_PATH)
.addConverterFactory(GsonConverterFactory.create());
Retrofit retrofit = builder.build();
ApiClient apiClient = retrofit.create`(ApiClient.class);
RequestBody filePart = RequestBody.create(/*MediaType.parse(context.getContentResolver().getType(Uri.parse(photoDetails.getImageUrl())))*/
MediaType.parse("image/*"),
file);
MultipartBody.Part fileMultiPart = MultipartBody.Part.createFormData("photo", file.getName(), filePart);
Call<PhotoResponseModel> call = apiClient.uploadPhoto(id, imageId, fileMultiPart);
call.enqueue(new Callback<PhotoResponseModel>() {
#Override
public void onResponse(Call<PhotoResponseModel> call, Response<PhotoResponseModel> response) {
}
}
}
#Override
public void onFailure(Call<PhotoResponseModel> call, Throwable t) {
Log.d("Error", "onFailure: ");
}
});
}
Add dependencies to gradle
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
compile 'com.squareup.okhttp3:logging-interceptor:3.3.1'
check this link
https://futurestud.io/tutorials/retrofit-2-how-to-upload-files-to-server

java httpurlconnection "failed to read: line to long:"

I'm using httpurlconnection for uploading files to different servers.
For some hosts the following code is working and I'm able to upload files, but when I'm trying to upload to another host, I get an error message
"failed to read: line too long: \nContent-Disposition: form-data; name...
What does this error mean? I couldn't find any hints with google. Hope you can help. :)
private void upload(){
response = "";
DataOutputStream outputStream = null;
InputStream inputStream = null;
String twoHyphens = "--";
String boundary = "--------"+Long.toString(System.currentTimeMillis());
String lineEnd = "\n";
try {
File file = getFile();
StringBuffer sb = new StringBuffer();
sb.append(twoHyphens + boundary + lineEnd);
sb.append("Content-Disposition: form-data; name=\"file1\"; filename=\"" + getFilename() +"\"" + lineEnd);
sb.append("Content-Type: " + getMime() + lineEnd);
sb.append("Content-Transfer-Encoding: binary" + lineEnd);
sb.append(lineEnd);
FileInputStream fileInputStream = new FileInputStream(file);
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setFixedLengthStreamingMode((uploadContainer.getFilesize() + sb.length() + lineEnd.length() + twoHyphens.length() + boundary.length() + twoHyphens.length() + lineEnd.length()));
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("User-Agent", USER_AGENT);
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary="+boundary);
outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"file1\"; filename=\"" + getFilename() +"\"" + lineEnd);
outputStream.writeBytes("Content-Type: " + getMime() + lineEnd);
outputStream.writeBytes("Content-Transfer-Encoding: binary" + lineEnd);
outputStream.writeBytes(lineEnd);
int bytesRead = -1;
byte[] buffer = new byte[4096];
boolean cancelled = false;
while ((bytesRead = fileInputStream.read(buffer)) > 0){
outputStream.write(buffer, 0, bytesRead);
if(Thread.currentThread().isInterrupted()){
cancelled = true;
break;
}
}
if(cancelled == false){
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
outputStream.flush();
inputStream = connection.getInputStream();
response = convertStreamToString(inputStream);
inputStream.close();
} else {
// ...
}
fileInputStream.close();
} catch(Exception e) {/e.printStackTrace();
} finally {
try {
outputStream.close();
} catch (IOException e) {e.printStackTrace();
}
}
}
String lineEnd = "\n";
The problem is here. The line terminator in HTTP is defined as \r\n, not \n.

Upload file from android to ASP .net using http POST method

I need to upload my file android device to server using webservice. But unfortunately Im getting error while doing it.Please help me to clear this error.
Here is my java code:
public class HttpFileUpload implements Runnable {
URL connectURL;
String responseString;
String Title;
String Description;
byte[ ] dataToServer;
FileInputStream fileInputStream = null;
HttpFileUpload(String urlString, String vTitle, String vDesc){
try{
connectURL = new URL(urlString);
Title= vTitle;
Description = vDesc;
}catch(Exception ex){
Log.i("HttpFileUpload","URL Malformatted");
}
}
void Send_Now(FileInputStream fStream){
fileInputStream = fStream;
Sending();
}
void Sending(){
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
String iFileName = "ovicam_temp_vid.mp4";
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
String Tag="fSnd";
try
{
Log.e(Tag,"Starting Http File Sending to URL");
// Open a HTTP connection to the URL
HttpURLConnection conn = (HttpURLConnection)connectURL.openConnection();
// Allow Inputs
conn.setDoInput(true);
// Allow Outputs
conn.setDoOutput(true);
// Don't use a cached copy.
conn.setUseCaches(false);
// Use a post method.
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"title\""+ lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(Title);
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"description\""+ lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(Description);
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + iFileName +"\"" + lineEnd);
dos.writeBytes(lineEnd);
Log.e(Tag,"Headers are written");
// create a buffer of maximum size
int bytesAvailable = fileInputStream.available();
int maxBufferSize = 1024;
int bufferSize = Math.min(bytesAvailable, maxBufferSize);
byte[ ] buffer = new byte[bufferSize];
// read file and write it into form...
int bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0)
{
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable,maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0,bufferSize);
}
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// close streams
fileInputStream.close();
dos.flush();
Log.e(Tag,"File Sent, Response: "+String.valueOf(conn.getResponseCode()));
InputStream is = conn.getInputStream();
// retrieve the response from server
int ch;
StringBuffer b =new StringBuffer();
while( ( ch = is.read() ) != -1 ){ b.append( (char)ch ); }
String s=b.toString();
Log.i("Response",s);
dos.close();
}
catch (MalformedURLException ex)
{
Log.e(Tag, "URL error: " + ex.getMessage(), ex);
}
catch (IOException ioe)
{
ioe.printStackTrace();
Log.e(Tag, "IO error: " + ioe.getMessage(), ioe);
}
}
#Override
public void run() {
// TODO Auto-generated method stub
}
}
LogCat:
java.io.FileNotFoundException: http:///****8*******8/*****
at com.android.okhttp.internal.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:210)
at arun.com.test.HttpFileUpload.Sending(HttpFileUpload.java:118)
at arun.com.test.HttpFileUpload.Send_Now(HttpFileUpload.java:36)
the average REST webservice won't return a response body on POST/PUT, just a response status. You'd like to determine it instead of the body.
Replace
InputStream response = conn.getInputStream();
by
int status = conn.getResponseCode();
All available status codes and their meaning are available in the HTTP spec, as linked before. The webservice itself should also come along with some documentation which overviews all status codes supported by the webservice and their special meaning, if any.
If the status starts with 4nn or 5nn, you'd like to use getErrorStream() instead to read the response body which may contain the error details.
InputStream error = con.getErrorStream();
Taken from this answer

Upload multiple images from Android to PHP

Try to upload multiple images with one request but only the first image is uploaded.
This is the java code:
protected String doInBackground(String... args) {
String end = "\r\n";
String twoHyphens = "--";
String boundary = "******";
String result = "Ein Fehler ist aufgetreten";
String charset = "UTF-8";
String insertedReportID;
try
{
insertedReportID = args[0];
/* BEGIN - ADD LOGIN CREDENTIALS TO THE QUERY */
final String authKeyMail = "authMail";
final String authKeyPW = "authPW";
Context mContext = getContext();
SharedPreferences mPrefs = mContext.getSharedPreferences("privPrefs", Context.MODE_PRIVATE);
String email = mPrefs.getString(authKeyMail, "default");
String pw = mPrefs.getString(authKeyPW,"default");
HashMap<String, String> params = new HashMap<>();
params.put("emailadr", email);
params.put("passwrt", pw);
StringBuilder sbParams = new StringBuilder();
int i = 0;
for (String key : params.keySet()) {
try {
if (i != 0){
sbParams.append("&");
}
sbParams.append(key).append("=")
.append(URLEncoder.encode(params.get(key), charset));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
i++;
}
/* END - ADD LOGIN CREDENTIALS TO THE QUERY */
URL url = new URL(UPLOAD_URL);
HttpURLConnection httpURLConnection = (HttpURLConnection) url
.openConnection();
// allow input and output
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
httpURLConnection.setUseCaches(false);
// use POST way
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
httpURLConnection.setRequestProperty("Charset", "UTF-8");
httpURLConnection.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
DataOutputStream dos = new DataOutputStream(
httpURLConnection.getOutputStream());
//BEGIN - ADD LOGIN CREDENTIALS TO THE UPLOADER
dos.writeBytes(twoHyphens + boundary + end);
//"emailadr" MUST BE THE EXACT SAME NAME AS IN PHP $_POST['emailadr']
dos.writeBytes("Content-Disposition: form-data; name=\"emailadr\""+ end);
dos.writeBytes(end);
dos.writeBytes(email);
dos.writeBytes(end);
dos.writeBytes(twoHyphens + boundary + end);
//"passwrt" MUST BE THE EXACT SAME NAME AS IN PHP $_POST['passwrt']
dos.writeBytes("Content-Disposition: form-data; name=\"passwrt\""+ end);
dos.writeBytes(end);
dos.writeBytes(pw);
dos.writeBytes(end);
dos.writeBytes(twoHyphens + boundary + end);
//END - ADD LOGIN CREDENTIALS TO THE UPLOADER
//"playgroundID" MUST BE THE EXACT SAME NAME AS IN PHP $_POST['equipmentID']
dos.writeBytes("Content-Disposition: form-data; name=\"reportID\""+ end);
dos.writeBytes(end);
dos.writeBytes(insertedReportID);
dos.writeBytes(end);
dos.writeBytes(twoHyphens + boundary + end);
//END - ADD LOGIN CREDENTIALS TO THE UPLOADER
//"playgroundID" MUST BE THE EXACT SAME NAME AS IN PHP $_POST['equipmentID']
dos.writeBytes("Content-Disposition: form-data; name=\"imageCounter\""+ end);
dos.writeBytes(end);
dos.writeBytes(String.valueOf(uploadImages.size()));
dos.writeBytes(end);
dos.writeBytes(twoHyphens + boundary + end);
//END - ADD LOGIN CREDENTIALS TO THE UPLOADER
for(int j=0;j<uploadImages.size();j++){
//"image_file" MUST BE THE EXACT SAME NAME AS IN PHP $_FILES['image_file']
dos.writeBytes("Content-Disposition: form-data; name=\"image_file"+String.valueOf(j)+"\"; filename=\""
+ uploadImages.get(j).substring(uploadImages.get(j).lastIndexOf("/") + 1)
+ "\""
+ end);
dos.writeBytes(end);
FileInputStream fis = new FileInputStream(uploadImages.get(j));
byte[] buffer = new byte[8192]; // 8k
int count = 0;
while ((count = fis.read(buffer)) != -1)
{
dos.write(buffer, 0, count);
}
fis.close();
dos.writeBytes(end);
dos.writeBytes(twoHyphens + boundary + twoHyphens + end);
Log.d("asdasd", "image_file"+uploadImages.get(j));
}
dos.flush();
InputStream is = httpURLConnection.getInputStream();
InputStreamReader isr = new InputStreamReader(is, "utf-8");
BufferedReader br = new BufferedReader(isr);
result = br.readLine();
dos.close();
is.close();
httpURLConnection.disconnect();
} catch (Exception e)
{
e.printStackTrace();
}
return result;
}
Php Code Snippet:
if (isset($_POST)) {
$imageCounter = $_POST['imageCounter'];
for ($i = 0; $i < $imageCounter; $i++) {
if ($_POST['reportID'] == "") {
die('Hier ist etwas schiefgelaufen (Code 100)');
}
// check $_FILES['ImageFile'] not empty
if (!isset($_FILES['image_file'.$i]) || !is_uploaded_file($_FILES['image_file'.$i]['tmp_name'])) {
die('Image file is Missing!'); // output error when above checks fail.
}
//get uploaded file info before we proceed
$image_name = $_FILES['image_file'.$i]['name']; //file name
$image_size = $_FILES['image_file'.$i]['size']; //file size
$image_temp = $_FILES['image_file'.$i]['tmp_name']; //file temp
$image_size_info = getimagesize($image_temp); //gets image size info from valid image file
Now the problem is that only the first image is uploaded and entered into the db.
I think there is something wrong with both sides (Java/Php).
Firstly with java because I can only receive one image on the php side.
I also got this working with ajax by using such a form:
<form action="../php/ajax/views/reports/uploadReportImages.php" method="post" enctype="multipart/form-data" id="MyUploadForm">
<div class="form-group">
<span id="durchsuchenBtn" class="btn btn-info btn-file">
<i class="fa fa-search fa-fw"></i> Durchsuchen <input name="image_file[]" id="imageInput" type="file" multiple="true">
</span>
</div>
</form>
Now I'm not sure how to translate name="image_file[]" id="imageInput" type="file" multiple="true" from the html form to java so I can send the images saved in "uploadImages"-String-ArrayList to the php script.
Any suggestion/help would be very nice.
As a little addition I don't want to use any library to handle the upload process...
I think everything is just fine except it only adds one file so the mistake must be here:
for(int j=0;j<uploadImages.size();j++){
//"image_file" MUST BE THE EXACT SAME NAME AS IN PHP $_FILES['image_file']
dos.writeBytes("Content-Disposition: form-data; name=\"image_file"+String.valueOf(j)+"\"; filename=\""
+ uploadImages.get(j).substring(uploadImages.get(j).lastIndexOf("/") + 1)
+ "\""
+ end);
dos.writeBytes(end);
FileInputStream fis = new FileInputStream(uploadImages.get(j));
byte[] buffer = new byte[8192]; // 8k
int count = 0;
while ((count = fis.read(buffer)) != -1)
{
dos.write(buffer, 0, count);
}
fis.close();
dos.writeBytes(end);
dos.writeBytes(twoHyphens + boundary + twoHyphens + end);
Log.d("asdasd", "image_file"+uploadImages.get(j));
}
Ok it hasn't worked because I arranged this line wrong:
dos.writeBytes(twoHyphens + boundary + twoHyphens + end);
Here is my working java code:
protected String doInBackground(String... args) {
String end = "\r\n";
String twoHyphens = "--";
String boundary = "******";
String result = "Ein Fehler ist aufgetreten";
String charset = "UTF-8";
String insertedReportID;
try
{
insertedReportID = args[0];
/* BEGIN - ADD LOGIN CREDENTIALS TO THE QUERY */
final String authKeyMail = "authMail";
final String authKeyPW = "authPW";
Context mContext = getContext();
SharedPreferences mPrefs = mContext.getSharedPreferences("privPrefs", Context.MODE_PRIVATE);
String email = mPrefs.getString(authKeyMail, "default");
String pw = mPrefs.getString(authKeyPW,"default");
HashMap<String, String> params = new HashMap<>();
params.put("emailadr", email);
params.put("passwrt", pw);
StringBuilder sbParams = new StringBuilder();
int i = 0;
for (String key : params.keySet()) {
try {
if (i != 0){
sbParams.append("&");
}
sbParams.append(key).append("=")
.append(URLEncoder.encode(params.get(key), charset));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
i++;
}
/* END - ADD LOGIN CREDENTIALS TO THE QUERY */
URL url = new URL(UPLOAD_URL);
HttpURLConnection httpURLConnection = (HttpURLConnection) url
.openConnection();
// allow input and output
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
httpURLConnection.setUseCaches(false);
// use POST way
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
httpURLConnection.setRequestProperty("Charset", "UTF-8");
httpURLConnection.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
DataOutputStream dos = new DataOutputStream(
httpURLConnection.getOutputStream());
//BEGIN - ADD LOGIN CREDENTIALS TO THE UPLOADER
dos.writeBytes(twoHyphens + boundary + end);
//"emailadr" MUST BE THE EXACT SAME NAME AS IN PHP $_POST['emailadr']
dos.writeBytes("Content-Disposition: form-data; name=\"emailadr\""+ end);
dos.writeBytes(end);
dos.writeBytes(email);
dos.writeBytes(end);
dos.writeBytes(twoHyphens + boundary + end);
//"passwrt" MUST BE THE EXACT SAME NAME AS IN PHP $_POST['passwrt']
dos.writeBytes("Content-Disposition: form-data; name=\"passwrt\""+ end);
dos.writeBytes(end);
dos.writeBytes(pw);
dos.writeBytes(end);
dos.writeBytes(twoHyphens + boundary + end);
//END - ADD LOGIN CREDENTIALS TO THE UPLOADER
//"playgroundID" MUST BE THE EXACT SAME NAME AS IN PHP $_POST['equipmentID']
dos.writeBytes("Content-Disposition: form-data; name=\"reportID\""+ end);
dos.writeBytes(end);
dos.writeBytes(insertedReportID);
dos.writeBytes(end);
dos.writeBytes(twoHyphens + boundary + end);
//END - ADD LOGIN CREDENTIALS TO THE UPLOADER
for(int j=0;j<uploadImages.size();j++){
//"image_file" MUST BE THE EXACT SAME NAME AS IN PHP $_FILES['image_file']
dos.writeBytes("Content-Disposition: form-data; name=\"image_file[]\"; filename=\""
+ uploadImages.get(j).substring(uploadImages.get(j).lastIndexOf("/") + 1)
+ "\""
+ end);
dos.writeBytes(end);
FileInputStream fis = new FileInputStream(uploadImages.get(j));
byte[] buffer = new byte[8192]; // 8k
int count = 0;
while ((count = fis.read(buffer)) != -1)
{
dos.write(buffer, 0, count);
}
fis.close();
dos.writeBytes(end);
dos.writeBytes(twoHyphens + boundary + end);
}
dos.close();
InputStream is = httpURLConnection.getInputStream();
InputStreamReader isr = new InputStreamReader(is, "utf-8");
BufferedReader br = new BufferedReader(isr);
result = br.readLine();
is.close();
httpURLConnection.disconnect();
} catch (Exception e)
{
e.printStackTrace();
}
return result;
}

Categories