English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
This article illustrates the implementation of image upload and download functions in Android programming. Share it with everyone for reference, as follows:
When implementing an Android web service client, such as a microblog or forum client, the upload and download of images are often used. Here, we introduce how to use HttpClient to implement the image upload and download function.
1 Image uploadWhen uploading an image, first obtain the image path, create a file, and convert the image to a byte stream and write it to the request, then send the request.
Client-side code:
File file = new File(imageUrl); String httpUrl = httpDomain+"AddImageServlet"+"?gid="+gid; HttpPost request = new HttpPost(httpUrl); HttpClient httpClient = new DefaultHttpClient(); FileEntity entity = new FileEntity(file,"binary",/octet-stream"); HttpResponse response; try { request.setEntity(entity); entity.setContentEncoding("binary"/octet-stream"); response = httpClient.execute(request); //If the return status is200, get the returned result if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){ ……//Image upload successful } } catch(Exception e){ }
The work done by the server-side is to receive the byte stream, write it into the file, and save the file in the corresponding folder on the server, and record the path of the file, and write the path of the image file into the database for saving.
Server-side code:
//Get the news id String gid = request.getParameter("gid"); String filePath = getRealPath(request) + "\\userpic\\"; // Define the maximum bytes of the uploaded file int MAX_SIZE = 102400 * 102400; // Declare the file reading class DataInputStream in = null; FileOutputStream fileOut = null; // Get the data type of the uploaded data from the client String contentType = request.getContentType(); if(contentType.indexOf("binary"/octet-(stream") >= 0){ // Read in the uploaded data in = new DataInputStream(request.getInputStream()); int formDataLength = request.getContentLength(); // If the image is too large if(formDataLength > MAX_SIZE){ String errormsg=("The number of bytes of the uploaded file cannot exceed" + MAX_SIZE); out.println(errormsg); return ; } // Save the data of the uploaded file byte dataBytes[] = new byte[formDataLength]; int byteRead = 0; int totalBytesRead = 0; // The data uploaded is stored in a byte array while(totalBytesRead < formDataLength){ byteRead = in.read(dataBytes,totalBytesRead,formDataLength); totalBytesRead += byteRead; } String fileName = filePath + gid+.png // Check if the directory of the uploaded file exists File fileDir = new File(filePath); if(!fileDir.exists()){ fileDir.mkdirs(); } // Create the writing class of the file fileOut = new FileOutputStream(fileName); // Data to save the file fileOut.write(dataBytes); fileOut.close(); //The path name of the file to be saved ……
2 Image downloadFirstly, obtain the image address of the network picture, send the request, and the server will return the byte stream of the picture. Use the BitmapFactory.decodeStream() method to convert the byte stream into an image and return it. The specific code is as follows:
//Obtain pictures from the network public Bitmap getGossipImage(String gid){ String httpUrl = httpDomain+"userpic/"+gid+.png Bitmap bitmap = null; HttpGet httpRequest = new HttpGet(httpUrl); //Obtain HttpClient object HttpClient httpclient = new DefaultHttpClient(); try { //Request httpClient, obtain HttpRestponse HttpResponse httpResponse = httpclient.execute(httpRequest); if(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK){ //Obtain relevant information Obtain HttpEntiy HttpEntity httpEntity = httpResponse.getEntity(); InputStream is = httpEntity.getContent(); bitmap = BitmapFactory.decodeStream(is); is.close(); } else { Toast.makeText(context, "Connection failed!", Toast.LENGTH_SHORT).show(); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return bitmap; }
Readers who are interested in more content related to Android can check the special topics on this site: 'Summary of Android Graphics and Image Processing Techniques', 'Android Development Tutorial for Beginners and Advanced', 'Summary of Android Debugging Techniques and Common Problem Solving Methods', 'Summary of Android Multimedia Operation Techniques (audio, video, recording, etc.)', 'Summary of Android Basic Component Usage', 'Summary of Android View View Techniques', 'Summary of Android Layout Layout Techniques', and 'Summary of Android Widget Usage'.
I hope the content described in this article will be helpful to everyone's Android program design.
Statement: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume any relevant legal liability. If you find any content suspected of copyright infringement, please send an email to notice#w3Please send an email to codebox.com (replace # with @ when sending an email) to report any violations, and provide relevant evidence. Once verified, this site will immediately delete the content suspected of infringement.