i am currently working on a programming-project in my school. I need to send an audio file (MIDI format) from the Client successfully to a Http Server. I already tried to do this myself and did much research on the internet and in the Stackoverflow forum. Currently it is possible to send the file from the client to the server, but on the server side, the audio file is not playable.
The following is the client-side-code:
private static void sendPOST() throws IOException{
final int mid = 1;
final String POST_URL = "http://localhost:8080/musiker/hörprobe?mid="+mid;
final File uploadFile = new File("C://Users//Felix Ulbrich//Desktop//EIS Prototype MIDIs//Pop//BabyOneMoreTime.mid");
String boundary = Long.toHexString(System.currentTimeMillis());
String CRLF = "\r\n";
String charset = "UTF-8";
URLConnection connection = new URL(POST_URL).openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
try (
OutputStream output = connection.getOutputStream();
PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, charset), true);
){
writer.append("--" + boundary).append(CRLF);
writer.append("Content-Disposition: form-data; name=\"binaryFile\"; filename=\"" + uploadFile.getName() + "\"").append(CRLF);
writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(uploadFile.getName())).append(CRLF);
writer.append("Content-Transfer-Encoding: binary").append(CRLF);
writer.append(CRLF).flush();
Files.copy(uploadFile.toPath(), output);
output.flush();
writer.append(CRLF).flush();
writer.append("--" + boundary + "--").append(CRLF).flush();
int responseCode = ((HttpURLConnection) connection).getResponseCode();
System.out.println(responseCode);
}
}
The following is the server-side-code:
int FILE_SIZE = Integer.MAX_VALUE-2;
int bytesRead = 0;
int current = 0;
FileOutputStream fos = null;
BufferedOutputStream bos = null;
byte[] mybytearray = new byte[FILE_SIZE];
String FILE_TO_RECEIVED = "C://root//m"+musikerid+"hp"+(hörprobenzaehler+1)+".mid";
File f = new File(FILE_TO_RECEIVED);
if(!f.exists()){
f.createNewFile();
}
InputStream input = t.getRequestBody();
fos = new FileOutputStream(FILE_TO_RECEIVED);
bos = new BufferedOutputStream(fos);
bytesRead = input.read(mybytearray,0,mybytearray.length);
current = bytesRead;
do{
bytesRead = input.read(mybytearray, current, mybytearray.length-current);
if(bytesRead >= 0){
current += bytesRead;
}
}while(bytesRead>-1);
bos.write(mybytearray,0,current);
bos.flush();
fos.close();
bos.close();
t.sendResponseHeaders(200, 0);
input.close();
I am pretty desperate right now, because i couldn't find any solution to this problem. I need to use an HTTP server, but i don't need to use the TCP protocol (which is used right now via streams). I thought about a solution via ftp so i don't need to convert the file to a byte-array first. I assume that the problem lies exactly there. The server can't create the audio-file (midi-file) correctly from the byte-array. If anyone of you knows of a solution. Pls, i need your help :D
Greetings, Gizpo
So I've dug deeper into the matter. I've found several problems:
You're mixing binary and character based I/O. While you get away with it on the client side, the server has a hard time dealing with this.
You forgot to specify the size of the file you're sending over to the server. On the server side you have no way of knowing (unless some one tells you beforehand) what the size (of the incoming file) will be.
I've edited your code and came up with this:
Client:
private static void sendPOST() throws IOException{
final int mid = 1;
final String POST_URL = "http://localhost:8080/musiker/hörprobe?mid="+mid;
final File uploadFile = new File("C://Users//Felix Ulbrich//Desktop//EIS Prototype MIDIs//Pop//BabyOneMoreTime.mid");
String boundary = Long.toHexString(System.currentTimeMillis());
String CRLF = "\r\n";
String charset = "UTF-8";
URLConnection connection = new URL(POST_URL).openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
try (
OutputStream output = connection.getOutputStream();
PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, charset), true);
) {
writer.append("--" + boundary).append(CRLF);
writer.append("Content-Disposition: form-data; name=\"binaryFile\"; filename=\"" + uploadFile.getName() + "\"").append(CRLF);
writer.append("Content-Length: " + uploadFile.length()).append(CRLF);
writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(uploadFile.getName())).append(CRLF);
writer.append("Content-Transfer-Encoding: binary").append(CRLF);
writer.append(CRLF).flush();
Files.copy(uploadFile.toPath(), output);
output.flush();
int responseCode = ((HttpURLConnection) connection).getResponseCode();
System.out.println("Response code: [" + responseCode + "]");
}
}
Server:
#Override
public void handle(HttpExchange t) throws IOException {
String CRLF = "\r\n";
int fileSize = 0;
String FILE_TO_RECEIVED = "C://root//m"+musikerid+"hp"+(hörprobenzaehler+1)+".mid";
File f = new File(FILE_TO_RECEIVED);
if (!f.exists()) {
f.createNewFile();
}
InputStream input = t.getRequestBody();
String nextLine = "";
do {
nextLine = readLine(input, CRLF);
if (nextLine.startsWith("Content-Length:")) {
fileSize =
Integer.parseInt(
nextLine.replaceAll(" ", "").substring(
"Content-Length:".length()
)
);
}
System.out.println(nextLine);
} while (!nextLine.equals(""));
byte[] midFileByteArray = new byte[fileSize];
int readOffset = 0;
while (readOffset < fileSize) {
int bytesRead = input.read(midFileByteArray, readOffset, fileSize);
readOffset += bytesRead;
}
BufferedOutputStream bos =
new BufferedOutputStream(new FileOutputStream(FILE_TO_RECEIVED));
bos.write(midFileByteArray, 0, fileSize);
bos.flush();
t.sendResponseHeaders(200, 0);
}
private static String readLine(InputStream is, String lineSeparator)
throws IOException {
int off = 0, i = 0;
byte[] separator = lineSeparator.getBytes("UTF-8");
byte[] lineBytes = new byte[1024];
while (is.available() > 0) {
int nextByte = is.read();
if (nextByte < -1) {
throw new IOException(
"Reached end of stream while reading the current line!");
}
lineBytes[i] = (byte) nextByte;
if (lineBytes[i++] == separator[off++]) {
if (off == separator.length) {
return new String(
lineBytes, 0, i-separator.length, "UTF-8");
}
}
else {
off = 0;
}
if (i == lineBytes.length) {
throw new IOException("Maximum line length exceeded: " + i);
}
}
throw new IOException(
"Reached end of stream while reading the current line!");
}
Related
Because some restrictions, I have to use plain Java sockets to download a file published in a http web site. This is how i am reading the response:
String serverIp = "192....";
int serverPort = 3000;
String url = "/path/to/file";
Socket socket = new Socket(serverIp, serverPort);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
String postContent = "content";
writer.write("POST " + url + " HTTP/1.0\r\n");
writer.write("Content-length: " + postContent.length() + "\r\n");
writer.write("\r\n");
writer.write(postContent);
writer.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
if (!line.trim().equals("")) {
//Process header
} else {
break;
}
}
int intChar = -1;
ByteArrayOutputStream out = new ByteArrayOutputStream();
while ((intChar = reader.read()) >= 0) {
out.write(intChar);
}
byte[] byteArray = out.toByteArray();
File outFile = new File("myfile.zip");
FileOutputStream fileOutputStream = new FileOutputStream(outFile);
fileOutputStream.write(byteArray);
fileOutputStream.close();
Every thing works fine, but the file myfile.zip is saved inconsistent. If I use unzip to uncompress the file, I get the error:
Archive: myfile.zip
error [myfile.zip]: missing 55053 bytes in zipfile
(attempting to process anyway)
error [myfile.zip]: start of central directory not found;
zipfile corrupt.
(please check that you have transferred or created the zipfile in the
appropriate BINARY mode and that you have compiled UnZip properly)
When I use curl to do the http post, myfile.zip download consistent and I can open it.
Any light?
Thanks guys. I used the suggestion of
President James K. Polk to write the following solution:
String serverIp = "192....";
int serverPort = 3000;
String url = "/path/to/file";
Socket socket = new Socket(serverIp, serverPort);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
String postContent = "content";
writer.write("POST " + url + " HTTP/1.0\r\n");
writer.write("Content-length: " + postContent.length() + "\r\n");
writer.write("\r\n");
writer.write(postContent);
writer.flush();
DataInputStream reader = new DataInputStream(socket.getInputStream());
int c = -1;
StringBuilder header = new StringBuilder();
while ((c = reader.read()) >= 0) {
header.append((char) c);
if (header.length() > 4 && header.substring(header.length() - 4).equals("\r\n\r\n")) {
break;
}
}
File outFile = new File("myfile.zip");
FileOutputStream fileOutputStream = new FileOutputStream(outFile);
while ((c = reader.read()) >= 0) {
fileOutputStream.write(c);
}
reader.close();
fileOutputStream.close();
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.
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 have a problem in sending the body of http response,and I think the problem in this line out.write(buffer, 0, bytes); please help me .
DataInputStream din = new DataInputStream(ClientConn.getInputStream());
OutputStream ot = ClientConn.getOutputStream();
BufferedOutputStream out = new BufferedOutputStream(ot);
String request = din.readLine().trim();
System.out.println(request);
StringTokenizer st = new StringTokenizer(request);
String header = st.nextToken();
System.out.println(header);
if (header.equals("GET")) {
String fileName = st.nextToken();
String file = fileName.substring(1, fileName.length());
System.out.println(file);
FileInputStream fin = null;
boolean fileExist = true;
try {
fin = new FileInputStream(file);
}
catch (Exception ex) {
fileExist = false;
}
String ServerLine = "Simple HTTP Server";
String StatusLine = null;
String ContentTypeLine = null;
String ContentLengthLine = null;
String ContentBody = null;
if (fileExist) {
StatusLine = "HTTP/1.0 200 OK";
ContentTypeLine = "Content-type: text/html";
ContentLengthLine = "Content-Length: " + (new Integer(fin.available()).toString());
} else {
StatusLine = "HTTP/1.0 200 OK";
ContentTypeLine = "Content-type: text/html";
ContentBody = "<HTML>" +
"<HEAD><TITLE>404 Not Found</TITLE></HEAD>" +
"<BODY>404 Not Found" +
"</BODY></HTML>";
ContentLengthLine = (new Integer(ContentBody.length()).toString());
}
out.write(StatusLine.getBytes());
out.write(ServerLine.getBytes());
out.write(ContentTypeLine.getBytes());
out.write(ContentLengthLine.getBytes());
// output.writeUTF(file);
if (fileExist) {
byte[] buffer = new byte[1024];
int bytes = 0;
while ((bytes = fin.read(buffer)) != -1) {
out.write(buffer, 0, bytes);
for (int iCount = 0; iCount < bytes; iCount++) {
int temp = buffer[iCount];
System.out.print((char) temp);
}
}
}
out.flush();
fin.close();
} else {
//out.write(ContentBody.getBytes());
}
out.close();
ClientConn.close();
Your header is not properly written into the OutputStream, you forget to write the EOL characters which are "\r\n" at the end of each line. And before starting to write the content of your body you need to write the EOL characters too.
In other words, you need to do something like this:
String eol = "\r\n";
Charset charset = Charset.forName("ASCII");
byte[] eolBytes = eol.getBytes(charset);
out.write(StatusLine.getBytes(charset));
out.write(eolBytes);
out.write( ServerLine.getBytes(charset));
out.write(eolBytes);
out.write(ContentTypeLine.getBytes(charset));
out.write(eolBytes);
out.write( ContentLengthLine.getBytes(charset));
out.write(eolBytes);
// End of the header
out.write(eolBytes);
// Here the body begin
Indeed your header must be encoded into ASCII.
Response update:
Other remarks regarding your code:
Use the method File#exists() to check if a file exist.
Use Files.getAttribute(Paths.get("/path/to/my/file"), "size") to get the size of your file
In case the file doesn't exist you just don't write the body in your current code.
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;
}
}