I want to upload file with other string data to the server in one request using HttpURLConnection (not using MultiPartEntityBuilder)...Currently I can send the file but not the other string data with it !! Here is my current code for sending the file to server :
HttpURLConnection.setFollowRedirects(false);
HttpURLConnection connection = null;
String fileName = sourceFile.getName();
try {
connection = (HttpURLConnection) new URL(FILE_UPLOAD_URL).openConnection();
connection.setRequestMethod("POST");
String boundary = "---------------------------boundary";
String tail = "\r\n--" + boundary + "--\r\n";
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
connection.setRequestProperty("token", sharedpreferences.getString("token", ""));
connection.setRequestProperty("app_version", app_version);
connection.setRequestProperty("api_version", api_version);
connection.setDoOutput(true);
String metadataPart = "--"
+ boundary
+ "\r\n"
+ "Content-Disposition: form-data; name=\"metadata\"\r\n\r\n"
+ ""
+ "\r\n";
String fileHeader1 = "--"
+ boundary
+ "\r\n"
+ "Content-Disposition: form-data; name=\"myFile\"; filename=\""
+ fileName
+ "\"\r\n"
+ "Content-Type: application/octet-stream\r\n"
+ "Content-Transfer-Encoding: binary\r\n";
long fileLength = sourceFile.length() + tail.length();
String fileHeader2 = "Content-length: " + fileLength + "\r\n";
String fileHeader = fileHeader1 + fileHeader2 + "\r\n";
String stringData = metadataPart + fileHeader;
long requestLength = stringData.length() + fileLength;
connection.setRequestProperty("Content-length", "" + requestLength);
connection.setFixedLengthStreamingMode((int) requestLength);
connection.connect();
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
out.writeBytes(stringData);
out.flush();
int progress = 0;
int bytesRead;
byte buf[] = new byte[1024];
BufferedInputStream bufInput = new BufferedInputStream(new FileInputStream(sourceFile));
while ((bytesRead = bufInput.read(buf)) != -1) {
// write output
out.write(buf, 0, bytesRead);
out.flush();
progress += bytesRead; // Here progress is total uploaded bytes
publishProgress((int) ((progress * 100) / sourceFile.length())); // sending progress percent to publishProgress
}
// Write closing boundary and close stream
out.writeBytes(tail);
out.flush();
out.close();
// Get server response
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
StringBuilder builder = new StringBuilder();
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} catch (Exception e) {
// Exception
} finally {
if (connection != null) connection.disconnect();
}
return null;
Any help would be appreciated !!Thank you...
Related
This is the way i have to send
I have tried with many answers but is not able to undersatnd the data value and the method used . i m new to multipart . Kindly help
This is the code it returns satus ok but returns response code as null
String charset = "UTF-8";
File uploadFile1 = new File("/storage/emulated/0/DCIM/Camera/IMG_20161127_101131.jpg");
String requestURL = "http://10.238.48.30:8081/socialapi/social/addimage/v1/51";
URL url = new URL(requestURL);
httpConn = (HttpURLConnection) url.openConnection();
httpConn.setRequestMethod("POST");
httpConn.setDoOutput(true);
httpConn.setDoInput(true);
outputStream = httpConn.getOutputStream();
writer = new PrintWriter(new OutputStreamWriter(outputStream, charset),
true);
String fileName = uploadFile1.getName();
writer.append(
"Content-Disposition: form-data; name=\"" + "uploadimage"
+ "\"; 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;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.flush();
inputStream.close();
writer.append(LINE_FEED);
writer.flush();
writer.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;
I'm using HttpUrlConnection to upload an image to a web server. When I run the app and attempt to upload an image I get a Http response 200 as well as receive the filename and the imageid of the supposed image that has been uploaded, but when i check the server the image was not uploaded. The filename and the id are now part of the list but when I attempt to retrieve the image it returns null.
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();
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("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary = " + boundary);
conn.setRequestProperty("X-Forwarded-For", myIp);
conn.setDoOutput(true);
File file = new File(filePath);
DataOutputStream ds = new DataOutputStream(conn.getOutputStream());
ds.writeBytes(twoHyphens + boundary + LINE_FEED);
ds.writeBytes("Content-Disposition: form-data; name=\"image\"; filename=\"" + file.getName() + "\"" + LINE_FEED);
ds.writeBytes("ContentType: image/peg" + LINE_FEED);
ds.writeBytes(twoHyphens + boundary + LINE_FEED);
FileInputStream fStream = new FileInputStream(file);
int bytesAvailable = fStream.available();
int maxBufferSize = 1024;
int bufferSize = Math.min(bytesAvailable, maxBufferSize);
byte[] buffer = new byte[bufferSize];
int bytesRead = fStream.read(buffer, 0, bufferSize);
while (bytesRead > 0)
{
ds.write(buffer, 0, bufferSize);
bytesAvailable = fStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fStream.read(buffer, 0, bufferSize);
}
ds.writeBytes(LINE_FEED);
ds.writeBytes(twoHyphens + boundary + twoHyphens + LINE_FEED);
fStream.close();
ds.flush();
ds.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;
}
I was able to fix the problem by using PrintWriter and OutputStream instead of DataOutputStream to pass the headers and the image.
I'm new to android development. I have this code to make a POST Request to a server with PHP.
HttpURLConnection conn;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = Long.toHexString(System.currentTimeMillis());
File sourceFile = new File(sourceFileUri);
if (!sourceFile.isFile()) {
dialog.dismiss();
Log.e(MainActivity.TAG, "Source File not exist :" + imagepath);
uploadButton.setEnabled(true);
return 0;
} else {
try {
postName = "Filedata[]";
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(upLoadServerUri);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("POST");
String cookie = CookieManager.getInstance().getCookie(upLoadServerUri);
conn.setRequestProperty("Cookie", cookie);
conn.setRequestProperty("User-Agent", MainActivity.userAgent);
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
conn.setRequestProperty(postName, sourceFileUri);
String charset = "UTF-8";
OutputStream output = conn.getOutputStream();
PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, charset), true);
// Send normal param.
writer.append(twoHyphens).append(boundary).append(lineEnd);
writer.append("Content-Disposition: form-data; name=\"to\"").append(lineEnd);
writer.append("Content-Type: text/plain; charset=").append(charset).append(lineEnd);
writer.append(lineEnd).append(id).append(lineEnd).flush();
writer.append(twoHyphens).append(boundary).append(lineEnd);
writer.append("Content-Disposition: form-data; name=\"content\"").append(lineEnd);
writer.append("Content-Type: text/plain; charset=").append(charset).append(lineEnd);
writer.append(lineEnd).append("image").append(lineEnd).flush();
// Send the picture
writer.append(twoHyphens).append(boundary).append(lineEnd);
writer.append("Content-Disposition: form-data; name=\"" + postName + "\"; filename=\"" + sourceFileUri + "\"").append(lineEnd);
writer.append("Content-Type: ").append(HttpURLConnection.guessContentTypeFromName(sourceFileUri)).append(lineEnd);
writer.append("Content-Transfer-Encoding: binary").append(lineEnd);
writer.append(lineEnd).flush();
copyFile(fileInputStream, output);
output.flush();
writer.append(lineEnd).flush();
// End of multipart/form-data.
writer.append(twoHyphens).append(boundary).append(twoHyphens).append(lineEnd);
// Responses from the server (code and message)
serverResponseCode = conn.getResponseCode();
// final String serverResponseMessage = conn.getResponseMessage();
InputStream stream = conn.getInputStream();
InputStreamReader isReader = new InputStreamReader(stream);
// put output stream into a string
BufferedReader br = new BufferedReader(isReader);
String serverResponsePre = "";
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
serverResponsePre += line;
}
final String serverResponse = serverResponsePre;
if (serverResponseCode == 200) {
Toast.makeText(Uploader.this, "File Upload Complete:" + serverResponse, Toast.LENGTH_LONG).show();
}
fileInputStream.close();
this.finish();
}catch(MalformedURLException ex){
dialog.dismiss();
ex.printStackTrace();
Log.e(MainActivity.TAG, "error: " + ex.getMessage(), ex);
uploadButton.setEnabled(true);
}catch(Exception e){
dialog.dismiss();
e.printStackTrace();
Toast.makeText(Uploader.this, "Got Exception : see logcat ", Toast.LENGTH_LONG).show();
Log.e(MainActivity.TAG, "Exception : " + e.getMessage(), e);
uploadButton.setEnabled(true);
}
dialog.dismiss();
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
}
On the android side, no error is thrown. On the PHP Side, $_FILES["Filedata"] is set, but the size of the file is 0 and no tmp_name is set. Am I missing something? I can't spot the error. Thank you in advance.
I am trying to upload a file to a server with following code, the upload works, but the payload is added to the file, you can see it for example uploading a text file:
private Integer doFileUpload(final String urlServer) {
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
FileInputStream fileInputStream = null;
final String pathToOurFile = mFileInfo.getProviderPath();
final String lineEnd = "\r\n";
final String twoHyphens = "--";
final String boundary = "*****";
int fileLength;
int bytesToRead, bufferSize;
final long fileSize;
byte[] buffer;
final int maxBufferSize = 1 * 1024 * 1024;
try {
final File file = new File(pathToOurFile);
fileInputStream = new FileInputStream(file);
final URL url = new URL(urlServer);
connection = (HttpURLConnection) url.openConnection();
final String[] payload = { twoHyphens + boundary + lineEnd,
"Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + pathToOurFile + "\"" + lineEnd, lineEnd, lineEnd,
twoHyphens + boundary + twoHyphens + lineEnd };
int payloadLength = 0;
for (final String string : payload) {
payloadLength += string.getBytes("UTF-8").length;
}
Logger.d(AsyncEgnyteUploadFile.LOGGING_TAG, "payload length: " + payloadLength);
fileLength = (int) file.length();
Logger.d(AsyncEgnyteUploadFile.LOGGING_TAG, "bytes: " + fileLength);
connection.setFixedLengthStreamingMode(fileLength + payloadLength);
fileSize = fileLength;
// Allow Inputs & Outputs
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setReadTimeout(5000);
connection.setConnectTimeout(5000);
connection.setRequestProperty("Authorization", "Bearer " + mToken);
// Enable POST method
connection.setRequestMethod(HttpPost.METHOD_NAME);
connection.setRequestProperty("Connection", "close");
// This header doesn't count to the number of bytes being sent.
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
connection.connect();
outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.writeBytes(payload[0]);
outputStream.writeBytes(payload[1]);
outputStream.writeBytes(payload[2]);
bufferSize = Math.min(fileLength, maxBufferSize);
buffer = new byte[bufferSize];
long totalBytesRead = 0;
long lastProgressTime = 0;
// Read file
bytesToRead = fileInputStream.read(buffer, 0, bufferSize);
boolean stopUploading = (FileState.UPLOADING != mFileInfo.getState() || isCancelled());
while (bytesToRead > 0 && !stopUploading)
{
outputStream.write(buffer);
totalBytesRead += bytesToRead;
Logger.d(AsyncEgnyteUploadFile.LOGGING_TAG, "bytes written: " + totalBytesRead);
final long now = System.currentTimeMillis();
bufferSize = (int) Math.min(fileLength - totalBytesRead, maxBufferSize);
buffer = new byte[bufferSize];
bytesToRead = fileInputStream.read(buffer, 0, bufferSize);
}
outputStream.writeBytes(payload[3]);
outputStream.writeBytes(payload[4]);
// Responses from the server (code and message)
final int serverResponseCode = connection.getResponseCode();
if (serverResponseCode == HttpStatus.SC_OK || serverResponseCode == HttpStatus.SC_CREATED) {
mAlreadyUploaded = true;
return JBError.JBERR_SUCCESS;
} else {
Log.e(AsyncEgnyteUploadFile.LOGGING_TAG, "error code: " + serverResponseCode);
return serverResponseCode;
}
} catch (final SocketTimeoutException e) {
..
} catch (final UnknownHostException e) {
..
} catch (final SocketException e) {
..
} catch (final IOException e) {
..
} catch (final Exception ex) {
..
} finally {
closeAll(connection, fileInputStream, outputStream);
}
}
Uploading a text file with only 12345 inside with this code results in following:
--*****
Content-Disposition: form-data; name="uploadedfile";filename="/storage/emulated/0/Download/3.txt"
12345
--*****--
What am I doing wrong?
You copy code is wrong. This is how to copy between streams in Java:
while ((count = in.read(buffer)) > 0)
{
out.write(buffer, 0, count);
}
Notes:
You must check all reads for end of stream.
You must use the read count in the write() method.
You don't need a new buffer per read, and you don't need a buffer the size of the file. This will work with any buffer size greater than zero. I usually use 8192.
I suspect that your server is not designed / configured to handle "multi-part" uploads.
It certainly looks like it is treating this as a plain upload ... and I cannot see anything wring with the multi-part encapsulation.
(EJP is correct, but that is not what is causing your problem here. Your example shows that all of the characters were sent ...)
public static String fileUploadFromPath(String url, String path) throws Throwable {
System.out.println("IN fileUploadFromPath ");
String responseData = "";
String NL = System.getProperty("line.separator");
try {
System.out.println("url ************ " + url);
File file = new File(path);
System.out.println("file ************ " + file.getAbsolutePath()
+ " : " + file.exists());
StringBuilder text = new StringBuilder();
if (file.exists()) {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append(NL);
}
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(url);
// System.out.println("postRequest ************ " +
// postRequest);
MultipartEntity multipartContent = new MultipartEntity();
ByteArrayBody key = new ByteArrayBody(text.toString()
.getBytes(), AgricultureUtils.getInstance()
.getTimeStamp() + ".3gp");
multipartContent.addPart(AgricultureUtils.getInstance()
.getTimeStamp() + ".3gp", key);
postRequest.setEntity(multipartContent);
HttpResponse response = httpClient.execute(postRequest);
BufferedReader in = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String content = "";
while ((content = in.readLine()) != null) {
sb.append(content + NL);
}
in.close();
/*
* File myDir = new File(Constants.dirctory); if
* (!myDir.exists()) { myDir.mkdirs(); } File myFile = new
* File(myDir, fileName); FileOutputStream mFileOutStream = new
* FileOutputStream(myFile);
* mFileOutStream.write(sb.toString().getBytes());
* mFileOutStream.flush(); mFileOutStream.close();
*/
System.out.println("response " + sb);
}
} catch (Throwable e) {
System.out.println("Exception In Webservice ----- " + e);
throw e;
}
return responseData;
}
I want to upload an audio file into server.
I am able upload audio file to server through above code but the file is not working(not playing in system). If u have any idea please help me.
You should be using neither FileReader nor StringBuilder here as it treats the data as characters (encoded according to the default system character set). Really, you should not be using a Reader at all. Binary data should be handled via InputStream, e.g.
final ByteArrayOutputStream out = new ByteArrayOutputStream();
try (final InputStream in = new FileInputStream(file)) {
final byte[] buf = new byte[2048];
int n;
while ((n = in.read(buf)) >= 0) {
out.write(buf, 0, n);
}
}
final byte[] data = out.toByteArray();
Did you check checksum on server? Is it arriving unmodified?
If not, try other method to post files. This one helped me a lot:
/**
* Post request (upload files)
* #param sUrl
* #param params Form data
* #param files
* #return
*/
public static HttpData post(String sUrl, Hashtable<String, String> params, ArrayList<File> files) {
HttpData ret = new HttpData();
try {
String boundary = "*****************************************";
String newLine = "rn";
int bytesAvailable;
int bufferSize;
int maxBufferSize = 4096;
int bytesRead;
URL url = new URL(sUrl);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);
con.setRequestMethod("POST");
con.setRequestProperty("Connection", "Keep-Alive");
con.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
DataOutputStream dos = new DataOutputStream(con.getOutputStream());
//dos.writeChars(params);
//upload files
for (int i=0; i<files.size(); i++) {
Log.i("HREQ", i+"");
FileInputStream fis = new FileInputStream(files.get(i));
dos.writeBytes("--" + boundary + newLine);
dos.writeBytes("Content-Disposition: form-data; "
+ "name="file_"+i+"";filename=""
+ files.get(i).getPath() +""" + newLine + newLine);
bytesAvailable = fis.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
byte[] buffer = new byte[bufferSize];
bytesRead = fis.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fis.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fis.read(buffer, 0, bufferSize);
}
dos.writeBytes(newLine);
dos.writeBytes("--" + boundary + "--" + newLine);
fis.close();
}
// Now write the data
Enumeration keys = params.keys();
String key, val;
while (keys.hasMoreElements()) {
key = keys.nextElement().toString();
val = params.get(key);
dos.writeBytes("--" + boundary + newLine);
dos.writeBytes("Content-Disposition: form-data;name=""
+ key+""" + newLine + newLine + val);
dos.writeBytes(newLine);
dos.writeBytes("--" + boundary + "--" + newLine);
}
dos.flush();
BufferedReader rd = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
ret.content += line + "rn";
}
//get headers
Map<String, List<String>> headers = con.getHeaderFields();
Set<Entry<String, List<String>>> hKeys = headers.entrySet();
for (Iterator<Entry<String, List<String>>> i = hKeys.iterator(); i.hasNext();) {
Entry<String, List<String>> m = i.next();
Log.w("HEADER_KEY", m.getKey() + "");
ret.headers.put(m.getKey(), m.getValue().toString());
if (m.getKey().equals("set-cookie"))
ret.cookies.put(m.getKey(), m.getValue().toString());
}
dos.close();
rd.close();
} catch (MalformedURLException me) {
} catch (IOException ie) {
} catch (Exception e) {
Log.e("HREQ", "Exception: "+e.toString());
}
return ret;
}
This is taken from:
http://moazzam-khan.com/blog/?p=490
Check link for dependencies and usage.