There are two ways to upload pictures of Android, one is to upload them in a file stream, and the images are converted into binary. The other is to turn the picture into Base64 way upload, this blog I only introduce file stream, about Base64 way will be introduced in the next blog!
The first is Android; image upload we need a path to the image, the same as the call to the local album or take pictures can return the picture path, this is not said here; Suppose we get the picture path to Picpath;
Here is the Android code:
First, we want to encapsulate the data data to be sent encapsulated and then use String Path=urlencodedutils.format (Parameters, "UTF-8"), to encode, and then the thread to send the data
Activity
Encapsulating data
@SuppressLint ("SimpleDateFormat")
Public String Getrubbishifo () throws IOException {
Final list<namevaluepair> Parameters = new arraylist<namevaluepair> ();
Parameters.Add (New Basicnamevaluepair ("Runame", Thingname.gettext ()
. toString (). Trim ()));
Parameters.Add (New Basicnamevaluepair ("Ruleibie", Fenlei
. GetSelectedItem (). toString ()));
Parameters.Add (New Basicnamevaluepair ("Rubeizhu", Beizhu.gettext ()
. toString (). Trim ()));
Parameters.Add (New Basicnamevaluepair ("Rufreetime", FreeTime
. GetSelectedItem (). toString ()));
Parameters.Add (New Basicnamevaluepair ("Userphone", Userphone));
Parameters.Add (New Basicnamevaluepair ("Address", Address.gettext ()
. toString (). Trim ()));
Parameters.Add (New Basicnamevaluepair ("username", username));
Parameters.Add (New Basicnamevaluepair ("Rudate", ""));
System.out.println ("Parameters:" + Parameters);
String Path=urlencodedutils.format (Parameters, "UTF-8");
System.out.println (path+ "0000000000000000000");
return path;
}
Handler MyHandler = new Handler () {
public void Handlemessage (Message msg) {
String text = (string) msg.obj;
if (text.equals ("yes")) {
LOG.D ("Click", "not empty");
Toast.maketext (Getapplicationcontext (), "published Successfully!!!" ", Toast.length_short)
. Show ();
} else {
Toast.maketext (Getapplicationcontext (), "Publish Failed!!!" ",
Toast.length_long). Show ();
}
};
};
Submit data
Class Tijiaolistener implements Onclicklistener {
@Override
public void OnClick (View v) {
TODO auto-generated Method Stub
New Thread (New Runnable () {
@Override
public void Run () {
TODO auto-generated Method Stub
Uploadfile_image up=new uploadfile_image ();
try {
String Path = Getrubbishifo ();
String restr=up.uploadfile (httppath.fabu_path+ "?" +path, Picpath);//Httppath.fabu_path is the path,Put the encapsulated dataPathTied to the path and passed to the server,Picpath as Picture path
Message message = Myhandler.obtainmessage ();
Message.obj = Restr;
Myhandler.sendmessage (message);
} catch (IOException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}
}). Start ();
Below is the tool class Uploadfile_image up is the picture format quasi-change way;
Package com.back.util;
Import Java.io.DataOutputStream;
Import Java.io.FileInputStream;
Import Java.io.InputStream;
Import java.net.HttpURLConnection;
Import Java.net.URL;
public class Uploadfile_image {
Private String NewName = "Image.jpg";
/* Method of uploading files to server */
public string UploadFile (String actionurl,string picpath)
{
String end = "\ r \ n";
String Twohyphens = "--";
String boundary = "* * * *";//Boundary identifier
Try
{
url url =new url (actionurl);
HttpURLConnection con= (httpurlconnection) url.openconnection ();
/* Allow input, Output, do not use cache */
Con.setdoinput (TRUE);//Allow input stream
Con.setdooutput (TRUE);//Allow output stream
Con.setusecaches (false);//cache is not allowed
/* Set the transferred Method=post */
Con.setrequestmethod ("POST");
/* Setrequestproperty SET Encoding */
Con.setrequestproperty ("Connection", "keep-alive");
Con.setrequestproperty ("Charset", "UTF-8");
Con.setrequestproperty ("Content-type",//"Multipart/form-data" This parameter to illustrate that we pass the file is not a string
"multipart/form-data;boundary=" +boundary);
/* Set DataOutputStream */
DataOutputStream ds =
New DataOutputStream (Con.getoutputstream ());
Ds.writebytes (twohyphens + boundary + end);
Ds.writebytes ("Content-disposition:form-data;") +
"Name=\" file1\ "filename=\" "+
NewName + "\" "+ end);
Ds.writebytes (end);
/* Get the file FileInputStream */
FileInputStream fstream =new FileInputStream (Picpath);
/* Set 1024bytes per write */
int buffersize = 1024;
byte[] buffer =new byte[buffersize];
int length =-1;
/* Read data from file to buffer */
while (length = fstream.read (buffer))!=-1)
{
/* Write the data into DataOutputStream */
Ds.write (buffer, 0, length);
}
Ds.writebytes (end);
Ds.writebytes (twohyphens + boundary + twohyphens + end);
/* Close streams */
Fstream.close ();
Ds.flush ();
/* Get response content */
InputStream is = Con.getinputstream ();
int ch;
StringBuffer b =new StringBuffer ();
while ((ch = is.read ())!=-1)
{
B.append ((char) ch);
}
/* Show Response on Dialog */
ShowDialog ("Upload succeeded" +b.tostring (). Trim ());
/* Close DataOutputStream */
Ds.close ();
Returns the information returned by the client
Return b.tostring (). Trim ();
}
catch (Exception e)
{
ShowDialog ("Upload failed" +e);
return null;
}
}
}
Android end;
Below is the server-side code
Package Cn.back.servlet.app;
Import Java.io.File;
Import java.io.IOException;
Import Java.io.OutputStream;
Import Java.io.PrintWriter;
Import Java.net.URLDecoder;
Import Java.text.DateFormat;
Import Java.text.SimpleDateFormat;
Import Java.util.Date;
Import Java.util.Iterator;
Import java.util.List;
Import javax.servlet.ServletException;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;
Import Org.apache.commons.fileupload.DiskFileUpload;
Import Org.apache.commons.fileupload.FileItem;
Import cn.back.domin.Things;
Import Cn.back.service.backservice;
Import CN.BACK.SERVICE.BACKSERVICEIMP;
public class Uploadimageapp extends HttpServlet {
private String name;
public void doget (HttpServletRequest request, httpservletresponse response)
Throws Servletexception, IOException {
DoPost (request, response);
}
public void DoPost (HttpServletRequest request, httpservletresponse response)
Throws Servletexception, IOException {
Accept Pictures
String temp = request.getsession (). Getservletcontext (). Getrealpath ("/")
+ "temp"; Temp directory
System.out.println ("temp=" + temp);
String LoadPath = Request.getsession (). Getservletcontext ()
. Getrealpath ("/")
+ "imagething"; Upload a file to store directory
System.out.println ("loadpath=" + LoadPath);
Diskfileupload fu = new Diskfileupload ();
Fu.setsizemax (1 * 1024 * 1024); Set allow user to upload file size in bytes
Fu.setsizethreshold (4096); Set up to allow only data stored in memory, unit: bytes
Fu.setrepositorypath (temp); Set the directory where the data is stored in the hard disk once the file size exceeds the value of Getsizethreshold ()
Start reading upload information
int index = 0;
List fileitems = null;
try {
Fileitems = fu.parserequest (request);
System.out.println ("fileitems=" + fileitems);
} catch (Exception e) {
E.printstacktrace ();
}
Iterator iter = Fileitems.iterator (); Process each uploaded file in turn
while (Iter.hasnext ()) {
Fileitem item = (Fileitem) iter.next ();//Ignore all other form information that is not a file field
if (!item.isformfield ()) {
Name = Item.getname ();//Gets the upload file name, including the path
Name = Name.substring (name.lastindexof ("\ \") + 1);//extract file name from full path
Long size = Item.getsize ();
if ((name = = NULL | | name.equals (")) && size = = 0)
Continue
int point = Name.indexof (".");
Name= (New
Date ()). GetTime () +name.substring (Point,name.length ()) +index;
Name = (new Date ()). GetTime ()
+ name.substring (point, Name.length ());
index++;
File Fnew = new file (loadpath,name);
try {
Item.write (fnew);
} catch (Exception e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
else//Remove all form information that is not a file field
{
String Fieldvalue = Item.getstring ();
If the containing Chinese should be written as: (to UTF-8 encoding)
String fieldvalue = new String (item.getstring (). GetBytes (), "UTF-8");
}
}
Picture accepted.
Receive Data and store
String path= "/back/imagething/" +name;
Request.setcharacterencoding ("UTF-8");
Response.setcharacterencoding ("UTF-8");
Date now = new Date ();
DateFormat DataFormat = new SimpleDateFormat ("Yyyy/mm/dd hh:mm:ss");//2014/08/31//04:08:26 get time
String fabutime = Dataformat.format (now);
Backservice bs = new Backserviceimp ();
Things t = new things ();
T.setthingname (New String (Request.getparameter ("Runame"). GetBytes ("Iso_8859-1"), "UTF-8");
Because it is usedurlencodedutilsEncoding so decoding is more troublesome, about decoding I have a separate blog to write code
System.out.println (name+ "11111111111111111111111");
T.setthingleibie (New String (Request.getparameter ("Ruleibie"). GetBytes ("Iso_8859-1"), "UTF-8");
T.setthingbeizhu (New String (Request.getparameter ("Rubeizhu"). GetBytes ("Iso_8859-1"), "UTF-8");
T.setthingfreetime (New String (Request.getparameter ("Rufreetime"). GetBytes ("Iso_8859-1"), "UTF-8");
T.setthingimg (path);
T.setthingfabutime (Fabutime);
T.setusername (New String (Request.getparameter ("username"). GetBytes ("Iso_8859-1"), "UTF-8");
T.setuserphone (New String (Request.getparameter ("Userphone"). GetBytes ("Iso_8859-1"), "UTF-8");
T.setaddress (New String (Request.getparameter ("Address"). GetBytes ("Iso_8859-1"), "UTF-8");
int flag = Bs.addback (t);
if (flag! = 0) {
SYSTEM.OUT.PRINTLN ("App registration Success");
}else
{
System.out.println ("0000000000000");
}
Send data
Response.setcontenttype ("Text/plain");
Response.setcharacterencoding ("UTF-8");
PrintWriter out = Response.getwriter ();//Send data
Out.write ("yes");
Out.flush ();
Out.close ();
}
}
End of server end; Base64 upload will be written in the next blog post. If in doubt contact [email protected]
Android uploads images with upload data, file stream