android:使用http协议将图片上传到自己的服务器

时间:2021-11-07 12:15:47

    由于http只支持上传的数据转化为字符串,对于想直接上传图片较不容易,故可以先将其转化为字节流,再将字节流转化为字符串。在此过程中经常出现错误,故可以考虑先将其用base64进行加密编码,在服务器端或客户端在将其通过base64解码成字节流,进而再转为相应的图片文件。

如图:

  客户端主要代码:

 1 import java.io.ByteArrayOutputStream;
 2 import java.util.ArrayList;
 3 import java.util.List;
 4 
 5 import org.apache.http.HttpEntity;
 6 import org.apache.http.HttpResponse;
 7 import org.apache.http.NameValuePair;
 8 import org.apache.http.client.HttpClient;
 9 import org.apache.http.client.entity.UrlEncodedFormEntity;
10 import org.apache.http.client.methods.HttpPost;
11 import org.apache.http.impl.client.DefaultHttpClient;
12 import org.apache.http.message.BasicNameValuePair;
13 import org.apache.http.util.EntityUtils;
14 
15 import com.hexiaochun.utils.Base64Coder;
16 import android.graphics.Bitmap;
17 
18 public class updaImage {
19     public static void updata(Bitmap upbitmap) {
20 
21         ByteArrayOutputStream stream = new ByteArrayOutputStream();
22         upbitmap.compress(Bitmap.CompressFormat.JPEG, 60, stream);
23         byte[] b = stream.toByteArray();
24         /*
25          * 将图片流以字符串形式存储下来,base64coder是一个常用的编码类, 经常用于各种网络数据传输时用来加密和解密
26          * 用,用来确保数据的唯一性
27          */
28         String file = new String(Base64Coder.encodeLines(b));
29         HttpClient client = new DefaultHttpClient();
30         // 设置上传参数
31         List<NameValuePair> formparams = new ArrayList<NameValuePair>();
32         formparams.add(new BasicNameValuePair("file", file));
33         HttpPost post = new HttpPost(MainActivity.HOST);
34         UrlEncodedFormEntity entity;
35         try {
36             entity = new UrlEncodedFormEntity(formparams, "UTF-8");
37             post.addHeader("Accept", "text/javascript, text/html, application/xml, text/xml");
38             post.addHeader("Accept-Charset", "GBK,utf-8;q=0.7,*;q=0.3");
39             // 加消息报头,进行gzip压缩,提高网络开销
40             post.addHeader("Accept-Encoding", "gzip,deflate,sdch");
41             post.addHeader("Connection", "Keep-Alive");
42             post.addHeader("Cache-Control", "no-cache");
43             post.addHeader("Content-Type", "application/x-www-form-urlencoded");
44             post.setEntity(entity);
45 
46             HttpResponse response = client.execute(post);
47             System.out.println(response.getStatusLine().getStatusCode());
48             HttpEntity e = response.getEntity();
49             System.out.println(EntityUtils.toString(e));
50             if (200 == response.getStatusLine().getStatusCode()) {
51                 System.out.println("上传完成");
52             } else {
53                 System.out.println("上传失败");
54             }
55             client.getConnectionManager().shutdown();
56         } catch (Exception e) {
57             e.printStackTrace();
58         }
59 
60     }
61 
62 }

 

 

 

将图片进行压缩代码如下:

 

 1 import android.graphics.Bitmap;
 2 import android.graphics.Matrix;
 3 /**
 4  * 
 5  * 裁剪图片类
 6  * 
 7  */
 8 public class ZoomBitmap {
 9     /**
10      * 
11      * @param bgimage传入的图片
12      * @param newWidth需要裁剪原图的长
13      * @param newHeight
14      * @return 裁剪后的图片
15      */
16     public static Bitmap zoomImage(Bitmap bgimage, double newWidth,
17             double newHeight) {
18         // 获取这个图片的宽和高
19         float width = bgimage.getWidth();
20         float height = bgimage.getHeight();
21         // 创建操作图片用的matrix对象
22         Matrix matrix = new Matrix();
23         // 计算宽高缩放率
24         float scaleWidth = ((float) newWidth) / width;
25         float scaleHeight = ((float) newHeight) / height;
26         // 缩放图片动作
27         matrix.postScale(scaleWidth, scaleHeight);
28         Bitmap bitmap = Bitmap.createBitmap(bgimage, 0, 0, (int) width,
29                 (int) height, matrix, true);
30         return bitmap;
31     }
32 }

服务端主要代码:
 

 1 import java.io.File;
 2 import java.io.FileOutputStream;
 3 import java.io.IOException;
 4 
 5 import javax.servlet.ServletException;
 6 import javax.servlet.http.HttpServlet;
 7 import javax.servlet.http.HttpServletRequest;
 8 import javax.servlet.http.HttpServletResponse;
 9 
10 import com.hexiaochun.utils.Base64Coder;
11 
12 public class UpServer extends HttpServlet {
13 
14     private String file;
15 
22 
23     @Override
24     protected void doPost(HttpServletRequest req, HttpServletResponse resp)
25             throws ServletException, IOException {
26         file = req.getParameter("file");
27         if (file != null) {
28 
29             byte[] b = Base64Coder.decodeLines(file);
30             String filepath = req.getSession().getServletContext()
31                     .getRealPath("/files");
32             File file = new File(filepath);
33             if (!file.exists())
34                 file.mkdirs();
35             FileOutputStream fos = new FileOutputStream(file.getPath()
36                     + "/image" + (int) (Math.random() * 100) + ".bmp");
37             System.out.println(file.getPath());
38             fos.write(b);
39             fos.flush();
40             fos.close();
41         }
42     }
43 
44 }


end-------------------------------------------------------------------->