Demonstration-java, upload/download-java

Source: Internet
Author: User

Demonstration of the multi-media file upload/download interface for enterprise account-java, upload/download-java

After talking about this blog, the enterprise account interface is complete. All the children's shoes that have downloaded my source code know that the remarks in it are very detailed. Whenever I have read it several times, I will develop it myself, now I have fully developed these interfaces, and the rest is that you write your own functions, which is a breeze. I may focus on Android later, you are welcome to join us and study together. Thank you.

When using interfaces, enterprises can obtain and call multimedia files and multimedia messages through media_id. This interface allows enterprises to upload or download multimedia files.


Note,Each multimedia file (media_id) is automatically deleted three days after being uploaded to the server.To save server resources


Upload a media file:

/*** Upload a media file ** @ param accessToken interface Access Credential * @ param type: media file types, including image, voice, and video ), file * @ param media form-data specifies the ID of a media file, information such as filename, filelength, and content-type * @ param mediaFileUrl Media File url * restrictions on uploaded media files * image: 1 MB, supports JPG format * voice (voice): 2 MB. The playback length cannot exceed 60 s. supports AMR format * video (10 MB) and MP4 format * normal file (file): 10 MB **/public static WeixinMedia uploadMedia (String accessToken, String type, String MediaFileUrl) {WeixinMedia weixinMedia = null; // assembled request address String uploadMediaUrl = "https://qyapi.weixin.qq.com/cgi-bin/media/upload? Access_token = ACCESS_TOKEN & type = TYPE "; uploadMediaUrl = uploadMediaUrl. replace ("ACCESS_TOKEN", accessToken ). replace ("TYPE", type); // define the Data Separator String boundary = "------------ 7da2e536604c8"; try {URL uploadUrl = new URL (uploadMediaUrl); HttpURLConnection uploadConn = (HttpURLConnection) uploadUrl. openConnection (); uploadConn. setDoOutput (true); uploadConn. setDoInput (true); uploadConn. setRequestMethod ("POST ");/ /Set Request Header Content-TypeuploadConn.setRequestProperty ("Content-Type", "multipart/form-data; boundary =" + boundary ); // obtain the output stream uploaded by the media file (write data to the server) OutputStream outputStream = uploadConn. getOutputStream (); URL mediaUrl = new URL (mediaFileUrl); HttpURLConnection meidaConn = (HttpURLConnection) mediaUrl. openConnection (); meidaConn. setDoOutput (true); meidaConn. setRequestMethod ("GET"); // obtain the content type from the request header String contentType = MeidaConn. getHeaderField ("Content-Type"); // determine the file extension String fileExt = WeixinUtil Based on the Content Type. getFileEndWitsh (contentType); // The Request body starts outputStream. write ("--" + boundary + "\ r \ n "). getBytes (); outputStream. write (String. format ("Content-Disposition: form-data; name = \" media \ "; filename = \" file1 % s \ "\ r \ n", fileExt ). getBytes (); outputStream. write (String. format ("Content-Type: % s \ r \ n", contentType ). getBytes (); // get BufferedInputStream bis = new BufferedInputStream (meidaConn. getInputStream (); byte [] buf = new byte [8096]; int size = 0; while (size = bis. read (buf ))! =-1) {// write the media file to the output stream (write data to the server) outputStream. write (buf, 0, size);} // The Request body ends outputStream. write ("\ r \ n --" + boundary + "-- \ r \ n "). getBytes (); outputStream. close (); bis. close (); meidaConn. disconnect (); // obtain the input stream uploaded by the media file (read data from the server) InputStream inputStream = uploadConn. getInputStream (); InputStreamReader inputStreamReader = new InputStreamReader (inputStream, "UTF-8"); BufferedReader bufferedReader = new BufferedReader (InputStreamReader); StringBuffer buffer = new StringBuffer (); String str = null; while (str = bufferedReader. readLine ())! = Null) {buffer. append (str);} bufferedReader. close (); inputStreamReader. close (); // release the resource inputStream. close (); inputStream = null; uploadConn. disconnect (); // use JSON-lib to parse the returned result JSONObject jsonObject = JSONObject. fromObject (buffer. toString (); // test the printed result System. out. println ("Print Test Results" + jsonObject); weixinMedia = new WeixinMedia (); weixinMedia. setType (jsonObject. getString ("type"); // if ("thumb") is different from other types when the value of type is equal to the value of thumb ". equals (type) weixinMedia. setMediaId (jsonObject. getString ("thumb_media_id"); elseweixinMedia. setMediaId (jsonObject. getString ("media_id"); weixinMedia. setCreatedAt (jsonObject. getInt ("created_at");} catch (Exception e) {weixinMedia = null; String error = String. format ("failed to upload the media file: % s", e); System. out. println (error);} return weixinMedia ;}

Download a media file:

/*** Obtain the media file ** @ param accessToken interface Access Credential * @ param media_id media file id * @ param savePath file storage path on the server **/public static String downloadMedia (string accessToken, string mediaId, String savePath) {String filePath = null; // concatenate the request address String requestUrl = "https://qyapi.weixin.qq.com/cgi-bin/media/get? Access_token = ACCESS_TOKEN & media_id = MEDIA_ID "; requestUrl = requestUrl. replace ("ACCESS_TOKEN", accessToken ). replace ("MEDIA_ID", mediaId); System. out. println (requestUrl); try {URL url = new URL (requestUrl); HttpURLConnection conn = (HttpURLConnection) url. openConnection (); conn. setDoInput (true); conn. setRequestMethod ("GET"); if (! SavePath. endsWith ("/") {savePath + = "/";} // obtain the extension String fileExt = WeixinUtil Based on the content type. getFileEndWitsh (conn. getHeaderField ("Content-Type"); // use mediaId as the file name filePath = savePath + mediaId + fileExt; BufferedInputStream bis = new BufferedInputStream (conn. getInputStream (); FileOutputStream fos = new FileOutputStream (new File (filePath); byte [] buf = new byte [8096]; int size = 0; while (size = bis. read (buf ))! =-1) fos. write (buf, 0, size); fos. close (); bis. close (); conn. disconnect (); String info = String. format ("media file downloaded successfully, filePath =" + filePath); System. out. println (info);} catch (Exception e) {filePath = null; String error = String. format ("failed to download media file: % s", e); System. out. println (error);} return filePath ;}

Main example:

// Example public static void main (String [] args) {/*** upload a multimedia file */String access_token = WeixinUtil. getAccessToken (ParamesAPI. corpId, ParamesAPI. secret ). getToken (); // address WeixinMedia weixinMedia = uploadMedia (access_token, "image", "http: // localhost: 8080/weixinClient/images/weather3.jpg "); // media_idSystem.out.println ("media_id:" + weixinMedia. getMediaId (); // type System. out. println ("type:" + weixinMedia. getType ());// Timestamp System. out. println ("timestamp:" + weixinMedia. getCreatedAt (); // print the result if (null! = WeixinMedia) {System. out. println ("uploaded successfully! ");} Else {System. out. println (" Upload Failed! ");} System. out. println ("dividing line ************************************ **************************************** ***************"); /*** download the multimedia file */String savePath = downloadMedia (access_token, weixinMedia. getMediaId (), "E:/download"); System. out. println ("the local address saved after the download is successful is:" + savePath );}

Print the results of the local test:



After the download is successful, save the image to the local image address:



Okay. Now all the interfaces are finished. I wish everyone could follow the source code and my blog to learn how to develop them independently and become a developer. Hey, thank you!



On the Development Platform, there is an interface for uploading multimedia files. I am using java for development. How can I achieve this in the background? The Code is as follows:

/*** Upload the file to the server * @ param fileType file type * @ param filePath file path * @ return JSONObject * @ throws Exception */public static JSONObject send (String fileType, string filePath) throws Exception {String result = null; File file = new File (filePath); if (! File. exists () |! File. isFile () {throw new IOException ("file does not exist");}/*** Part 1 */URL urlObj = new URL ("file.api.weixin.qq.com/..token=" + getAccess_token () + "& type =" + fileType + ""); HttpURLConnection con = (HttpURLConnection) urlObj. openConnection (); con. setRequestMethod ("POST"); // submit the form in Post mode. The default get method is con. setDoInput (true); con. setDoOutput (true); con. setUseCaches (false); // The cache cannot be used in post mode. // set the request header information con. setRequestProperty ("Connection", "Keep-Alive"); con. setRequestProperty ("Charset", "UTF-8"); // set the BOUNDARY String BOUNDARY = "----------" + System. currentTimeMillis (); con. setRequestProperty ("Content-Type", "multipart/form-data; boundary =" + BOUNDARY); // Request body information // The first part: stringBuilder sb = ...... remaining full text>

To publish a service in java, you can use interfaces to view multimedia files.

Web Service?
The transmission efficiency of the soap protocol (underlying XML transmission) is definitely greatly reduced.
Only binary data can be transmitted. If the java background is used, the binary data transmission protocol of hessian can be used. No, hessian. I have never used it. You can check it online. The configuration should give you several links:
1. www.iteye.com/topic/14887 use spirng and hessian to build distributed applications (remote interfaces)
2. hessian.caucho.com/hessian Official Website
In multimedia format, Adobe's AMF (equivalent to Web service) protocol can also be considered, but I do not know that Apple does not support Flash, and Apple devices do not support Flash.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.