Issue
I need to upload an image. For that I have to pass an image and an ID to the server.
dos.writeBytes("Content-Disposition: form-data; name=\"file_name\";filename=\""
+ fileName + "\"" + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"" + stringFieldName + "\""+ lineEnd);
dos.writeBytes(lineEnd);
fileName
is the image path.
stringFieldName
is the user_id
My code is given below.
public void webservicePhp(Long userId, Bitmap bmp) {
String userIdParameter = String.valueOf(userId);
String fileName = "temporary_holder.jpg";
HttpURLConnection conn = null;
DataOutputStream dos = null;
DataInputStream inStream = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
String charset = "UTF-8";
String responseFromServer = "";
String stringFieldName = "user_id";
String sourceFileUri = HomeScreen.get_path();
String upLoadServerUri = "http://10.120.10.87:8080/ContactsManagerWeb/UploadImage";
File sourceFile = new File(sourceFileUri);
if (!sourceFile.isFile()) {
Log.e("Huzza", "Source File Does not exist");
return;
}
int serverResponseCode = 0;
try { // open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(upLoadServerUri);
conn = (HttpURLConnection) url.openConnection(); // Open a HTTP
// connection to
// the URL
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Accept-Charset", charset);
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("file_name", fileName);
conn.setRequestProperty("user_id", userIdParameter);
dos = new DataOutputStream(conn.getOutputStream());
dos.write(query.getBytes(charset));
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"file_name\";filename=\""
+ fileName + "\"" + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"" + stringFieldName + "\""+ lineEnd);
dos.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available(); // create a buffer of maximum size
bufferSize = (int) sourceFile.length();
System.out.println("BytesAvail" + bytesAvailable);
System.out.println("maxBufferSize" + maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
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);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
System.out.println("Upload file to serverHTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
// close streams
System.out.println("Upload file to server"+ fileName + " File is written");
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
ex.printStackTrace();
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
e.printStackTrace();
}
// this block will give the response of upload link
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
System.out.println("RESULT Message: " + line);
}
rd.close();
} catch (IOException ioex) {
Log.e("Huzza", "error: " + ioex.getMessage(), ioex);
}
return; // like 200 (Ok)
}
In my servlet I am not able to access the user_id parameter. It's not getting there.
Servlet.java
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
File filenameImg = null;
List<FileItem> items = null;
try {
items = new ServletFileUpload(new DiskFileItemFactory())
.parseRequest(request);
} catch (FileUploadException e) {
throw new ServletException("Cannot parse multipart request.", e);
}
for (FileItem item : items) {
if (item.isFormField()) {
// Process regular form fields here the same way as
// request.getParameter().
// You can get parameter name by
String fieldname = item.getFieldName();
String fieldvalue = item.getString();
System.out.println("user_id===fieldname====== "+fieldname);
System.out.println("user_id====fieldvalue===== "+fieldvalue);
// You can get parameter value by item.getString();
} else {
try{
// Process uploaded fields here.
String filename = FilenameUtils.getName(item.getName());
// Get filename.
String path = GetWebApplicationPathServlet.getContext().getRealPath("/images");
File file = new File(path,filename);
// Define destination file.
item.write(file);
System.out.println("filename: "+filename);
System.out.println("file: "+file);
request.setAttribute("image", file);
filenameImg = file;
// Write to destination file.
// request.setAttribute("image", filename);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
// Show result page.
System.out.println("request"+request.getAttribute("image"));
//response.setContentType("image/jpeg");
request.setAttribute("servletName", filenameImg);
getServletConfig().getServletContext().getRequestDispatcher(
"/result.jsp").forward(request,response);
}
if (item.isFormField()) {}
is returning false.
Please help.
Solution
If this is same with html form submit. Then you can try this.
In your if (item.isFormField()) {
in your Servlets do this.
String user_Id = null; //Create an instance of String variable before initializing (Optional)
if (item.isFormField()) {
if(item.getFieldName().contentEquals("name")){ //Check if the item in the loop is the user_id
user_id = item.getString(); //If yes store the value
}
} else { //continue with your current code
I run with the same problem before and this is the one worked for me. I'm not sure if this what you looking for, just have a try.
Answered By - ace