Is there a way to speedup the process of uploading an image to a web server. The app that I am developing takes too long to upload an image. My code works and I know that I am able to upload a image to the server successfully.
I based this code off of a tutorial that I found here.
public String uploadFile(String apiPath, String filePath, String type)
{
String path = "";
String result = "";
switch (type)
{
case "M":
path = "Merchant/" + apiPath;
break;
case "C":
path = "Customer/" + apiPath;
break;
}
Log.i(ApiSecurityManager.class.getSimpleName(), m_token);
String href = "http://tysomapi.fr3dom.net/" + path + "?token=" + m_token;
Log.i(ApiSecurityManager.class.getSimpleName(), href);
try
{
String myIp = getIp();
String charset = "UTF-8";
File file = new File(filePath);
PrintWriter writer;
OutputStream outputStream;
URL url = new URL(href);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("User-Agent", "java");
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("image", file.getName());
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary = " + boundary);
conn.setRequestProperty("X-Forwarded-For", myIp);
conn.setDoOutput(true);
outputStream = conn.getOutputStream();
writer = new PrintWriter(new OutputStreamWriter(outputStream, charset), true);
writer.append(twoHyphens + boundary + LINE_FEED);
writer.append("Content-Disposition: form-data; name=\"image\"; filename=\"" + file.getName() + "\"" + LINE_FEED);
writer.append("ContentType: image/peg" + LINE_FEED);
writer.append(twoHyphens + boundary + LINE_FEED);
writer.flush();
writer.append(twoHyphens + boundary + LINE_FEED);
writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
writer.append(LINE_FEED);
writer.flush();
FileInputStream inputStream = new FileInputStream(file);
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.flush();
inputStream.close();
writer.append(LINE_FEED);
writer.flush();
writer.append(LINE_FEED);
writer.append(twoHyphens + boundary + twoHyphens + LINE_FEED);
writer.close();
Log.i(getClass().getSimpleName(), "Response Code: " + conn.getResponseCode());
if (conn.getResponseCode() != HttpURLConnection.HTTP_OK)
{
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
while ((output = br.readLine()) != null)
{
result = result + output;
}
conn.disconnect();
}
catch (
MalformedURLException e
)
{
e.printStackTrace();
}
catch (
IOException e
)
{
e.printStackTrace();
}
return result;
}
Use this library:
https://github.com/gotev/android-upload-service/wiki
It will automatically handle URL connections, failures & retries.
Related
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);
}
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
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.
I want to connect to a web-service and send a big file, i use HttpURLConnection like this:
private void doFileUpload() {
HttpURLConnection conn = null;
DataOutputStream dos = null;
DataInputStream inStream = null;
String lineEnd = "\r\n";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 8 * 1024 * 1024;
FileInputStream fileInputStream;
try {
fileInputStream = new FileInputStream(new File(getRealPathFromURI(fileUri)));
URL url = new URL("https://url.com/service.asmx?op=Method");
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("SOAPAction", SOAP_ACTION);
conn.setRequestProperty("Host", "url.com");
conn.setRequestProperty("Content-Type", "text/plain; charset=utf-8");
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes("<?xml version=\"1.0\" encoding=\"utf-8\"?>" + lineEnd);
dos.writeBytes("<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/>"
+ lineEnd);
dos.writeBytes("<soap:Body>" + lineEnd);
dos.writeBytes("<IncluirMultimedia xmlns=/" + "www.url.es/>/" + lineEnd);
dos.writeBytes("<identificadorGUID>" + Guid + "<" + "/identificadorGUID>" + lineEnd);
dos.writeBytes("<numeroServicio>" + codigoServicio + "<" + "/numeroServicio>" + lineEnd);
dos.writeBytes("<contenido>" + ficheroAEnviar + "<" + "/contenido>" + lineEnd);
dos.writeBytes("<tipoMultimedia>" + "0" + "<" + "/tipoMultimedia>" + lineEnd);
dos.writeBytes("<coordenadaLatitud>" + "0.0" + "<" + "/coordenadaLatitud>" + lineEnd);
dos.writeBytes("<coordenadaLongitud>" + "0.0" + "<" + "/coordenadaLongitud>" + lineEnd);
dos.writeBytes("<extension>" + "mp4" + "<" + "/extension>" + lineEnd);
dos.writeBytes("<cuando>" + "0" + "<" + "/cuando>" + lineEnd);
dos.writeBytes("<IncluirMultimedia>" + lineEnd);
dos.writeBytes("</soap:Body>" + lineEnd);
dos.writeBytes("</soap:Envelope>");
buffer = new byte[8192];
bytesRead = 0;
while ((bytesRead = fileInputStream.read(buffer)) != -1) {
dos.write(buffer, 0, bytesRead);
}
BufferedReader r = new BufferedReader(new InputStreamReader(fileInputStream));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line);
}
fileInputStream.close();
dos.flush();
dos.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
try {
conn.getContentLength();
if (conn.getResponseCode() >= 400) {
inStream = new DataInputStream(conn.getInputStream());
}
else {
inStream = new DataInputStream(conn.getErrorStream());
}
inStream.close();
}
catch (IOException ioex) {
Log.e("Debug", "error: " + ioex.getMessage(), ioex);
}
}
And my soap-request must be:
POST /url/url.asmx HTTP/1.1
Host: url.es
Content-Type: text/xml; charset=utf-8
Content-Length: length
SOAPAction: "www.url.com/IncluirMultimedia"
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<IncluirMultimedia xmlns="www.url.es">
<identificadorGUID>string</identificadorGUID>
<numeroServicio>string</numeroServicio>
<contenido>base64Binary</contenido>
<tipoMultimedia>int</tipoMultimedia>
<coordenadaLatitud>string</coordenadaLatitud>
<coordenadaLongitud>string</coordenadaLongitud>
<extension>string</extension>
<cuando>int</cuando>
</IncluirMultimedia>
</soap:Body>
</soap:Envelope>
I cant use ksoap2 because i need to send a very large file and this causes OutOfMemoryError. That's why i need to use this class.
I'm getting error 415, what am i doing wrong ?
Try using:
conn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
You are sending xml, I guess the server expects it.
I'm trying to write a file and upload it, however, the file does not seem to be written properly (as later on that I need to upload it, it crashes and says no file). I'm following the guidelines of Google's documentation. Here's my code:
String fileLocation = "Hello";
String TESTSTRING = new String("Hello Android");
FileOutputStream fOut = openFileOutput(fileLocation, MODE_WORLD_READABLE);
fOut.write(TESTSTRING.getBytes());
fOut.close();
That's how I'm trying to upload:
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
DataInputStream inputStream = null;
String pathToOurFile = fileLocation;
String Tag = "UPLOADER";
HttpURLConnection conn = null;
String urlServer = "http://..."; //my server
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
try {
// ------------------ CLIENT REQUEST
Log.e(Tag, "Inside second Method");
FileInputStream fileInputStream = new FileInputStream(new File(fileLocation));
// open a URL connection to the Servlet
URL url = new URL(urlServer);
// 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("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: post-data; name=uploadedfile;filename="
+ fileLocation + "" + lineEnd);
dos.writeBytes(lineEnd);
Log.e(Tag, "Headers are written");
// create a buffer of maximum size
int bytesAvailable = fileInputStream.available();
int maxBufferSize = 1000;
// int bufferSize = Math.min(bytesAvailable, maxBufferSize);
byte[] buffer = new byte[bytesAvailable];
// read file and write it into form...
int bytesRead = fileInputStream.read(buffer, 0, bytesAvailable);
while (bytesRead > 0) {
dos.write(buffer, 0, bytesAvailable);
bytesAvailable = fileInputStream.available();
bytesAvailable = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bytesAvailable);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// close streams
Log.e(Tag, "File is written");
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
Log.e(Tag, "error: " + ex.getMessage(), ex);
}
catch (IOException ioe) {
Log.e(Tag, "error: " + ioe.getMessage(), ioe);
}
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
Log.e("Dialoge Box", "Message: " + line);
}
rd.close();
} catch (IOException ioex) {
Log.e("MediaPlayer", "error: " + ioex.getMessage(), ioex);
}
}
Here's the PHP code on the server:
$target_path = "./";
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
Instead of using
FileInputStream fileInputStream = new FileInputStream(new File(fileLocation));
use
FileInputStream fileInputStream = openFileInput(fileLocation);
try something like this:
fileLocation = context.getFilesDir() + "Hello";
I'm not sure that you can/should write files to the root directory like that.
Please, first Write a String like this, than you send the file to server. It will help some one.
String resp = "Hello Andrid!!!";
File file= new File("/sdcard/hello.xml");
FileOutputStream fos = new FileOutputStream(file);
try {
fos.write(resp.getBytes());
fos.flush();
fos.close();
Log.d("File Write is success","fine");
} catch (Exception e) {
Log.d("Error in File write: ", ""+e.getMessage());
} finally {
if (fos != null) {
fos = null;
}
}