Previous beta server upload downloaded demo test can optimize the code by being interested in uploading and downloading
public static Boolean uploadfile (file file, String URL) {
String CHARSET = "Utf-8";
Boolean upload = false;
FileInputStream FIS = null;
URL murl = null;
HttpURLConnection conn = null;
String boundary = Uuid.randomuuid (). toString (); Random generation of boundary markers
String PREFIX = "--", Line_end = "\ r \ n";
String content_type = "Multipart/form-data"; Content Type
try {
murl = new URL (URL);
conn = (httpurlconnection) murl.openconnection ();
Conn.setreadtimeout (5000); //
Conn.setconnecttimeout (5000);
Conn.setdoinput (TRUE); Allow input stream
Conn.setdooutput (TRUE); Allow output stream
Conn.setusecaches (FALSE); Caching is not allowed
Conn.setrequestmethod ("POST"); Request method
Conn.setrequestproperty ("Charset", Charset); Set encoding
Conn.setrequestproperty ("Connection", "keep-alive");
Conn.setrequestproperty ("Content-type", Content_Type + "; boundary=" + boundary);
if (file = null) {/** * files are not empty, package and upload the file */
DataOutputStream dos = new DataOutputStream (Conn.getoutputstream ());
StringBuffer sb = new StringBuffer ();
Sb.append (PREFIX); Sb.append (boundary);
Sb.append (Line_end);
/** * Note here: The value inside the name is the server side need key only this key can get the corresponding file * filename is the name of the file, including the suffix name, such as: Abc.png */
Sb.append ("Content-disposition:form-data; Name=\ "File\"; Filename=\ "" + file.getname () + "\" "+ line_end);
Sb.append ("Content-type:application/octet-stream; Charset= "+ charset + line_end);
Sb.append (Line_end); Dos.write (Sb.tostring (). GetBytes ());
InputStream is = new FileInputStream (file);
byte[] bytes = new byte[1024];
int len = 0; int send=0;
while (len = is.read (bytes))! =-1) {
System.out.println ("len:" + len);
Dos.write (bytes, 0, Len);
Send+=len; Dos.flush ();
}
Is.close ();
Dos.write (Line_end.getbytes ());
Byte[] End_data = (PREFIX + boundary + PREFIX + line_end). GetBytes ();
Dos.write (End_data); Dos.flush ();
/** * Get response code 200 = Success When the response succeeds, gets the stream of the response */
int res = Conn.getresponsecode ();
if (res = = 200) {
InputStream input = Conn.getinputstream ();
StringBuffer sb1 = new StringBuffer ();
int SS;
while (ss = Input.read ())! =-1) {
Sb1.append ((char) SS);
}
Upload = true;
}
}
} catch (Malformedurlexception e) {e.printstacktrace (); } catch (IOException e) {e.printstacktrace (); } return upload; }
About file Upload Download