• android 上传文件到服务器


    1、编写layout.xml

    <LinearLayout 
                 android:layout_width="match_parent"
                 android:layout_height="wrap_content"
                 android:orientation="horizontal">
                 <LinearLayout 
                     android:layout_width="match_parent"
                     android:layout_height="wrap_content"
                     android:layout_weight="1"                 
                     android:layout_marginRight="10dip"
                     android:orientation="vertical">                
                
                        <Button android:id="@+id/upload_btn"
                        android:layout_width="match_parent"
                        android:layout_height="24dip"
                        android:textSize="13sp"
                        android:textColor="#ffffff"                    
                        android:gravity="center"
                        android:background="@drawable/btn_bg_ora"
                        android:text="上传图片" />
                        
                      <ImageView android:id="@+id/img_view"
                        android:layout_width="match_parent"
                        android:layout_height="100dp"/>
                      
                 </LinearLayout>

    生成效果图如下

    2、编写提交图片到服务器 HttpUtils.java

     1 public class HttpUtils {
     2     /**** 作为标记 ****/
     3     private static final String TAG = "HttpUtils处理类";
     4 
     5     /** 用户识别 ****/
     6     public static final String User_Agent = "";
     7     public static final String BASE_URL = "http://192.169.1.189:8080/";
     8     
     9     
    10     private static final int TIME_OUT = 10 * 10000; // 超时时间
    11     private static final String CHARSET = "utf-8"; // 设置编码
    12     /**
    13      * 上传文件到服务器
    14      * @param file 需要上传的文件
    15      * @param RequestURL 请求的rul
    16      * @return 返回响应的内容
    17      */
    18     public static String uploadFile(File file, String RequestURL) {
    19         int res=0;
    20         String result = null;
    21         String BOUNDARY = UUID.randomUUID().toString(); // 边界标识 随机生成
    22         String PREFIX = "--", LINE_END = "
    ";
    23         String CONTENT_TYPE = "multipart/form-data"; // 内容类型
    24         
    25         try {
    26             URL url = new URL(RequestURL);
    27             HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    28             conn.setReadTimeout(TIME_OUT);
    29             conn.setConnectTimeout(TIME_OUT);
    30             conn.setDoInput(true); // 允许输入流
    31             conn.setDoOutput(true); // 允许输出流
    32             conn.setUseCaches(false); // 不允许使用缓存
    33             conn.setRequestMethod("POST"); // 请求方式
    34             conn.setRequestProperty("Charset", CHARSET); // 设置编码
    35             conn.setRequestProperty("connection", "keep-alive");
    36             conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary="+ BOUNDARY);
    37 
    38             if (file != null) {
    39                 /**
    40                  * 当文件不为空时执行上传
    41                  */
    42                 conn.connect();
    43                 DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
    44                 StringBuffer sb = new StringBuffer();
    45                 sb.append(PREFIX);
    46                 sb.append(BOUNDARY);
    47                 sb.append(LINE_END);
    48                 /**
    49                  * 这里重点注意: name里面的值为服务器端需要key 只有这个key 才可以得到对应的文件
    50                  * filename是文件的名字,包含后缀名
    51                  */
    52 
    53                 sb.append("Content-Disposition: form-data; name="image"; filename="" + file.getName() + """ + LINE_END);
    54                 sb.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINE_END);
    55                 sb.append(LINE_END);
    56                 dos.write(sb.toString().getBytes());    
    57                 InputStream is = new FileInputStream(file);
    58                 byte[] bytes = new byte[8*1024];
    59                 int len = 0;
    60                 while ((len = is.read(bytes)) != -1) {
    61                     dos.write(bytes, 0, len);
    62                 }
    63                 is.close();
    64                 dos.write(LINE_END.getBytes());
    65                 byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes();
    66                 dos.write(end_data);
    67                 dos.flush();
    68                 /**
    69                  * 获取响应码 200=成功 当响应成功,获取响应的流
    70                  */
    71                  res = conn.getResponseCode();
    72                 Log.e(TAG, "response code:" + res);
    73                 if (res == 200) {
    74                     Log.e(TAG, "request success");
    75                     InputStream input = conn.getInputStream();
    76                     StringBuffer sb1 = new StringBuffer();
    77                     int ss;
    78                     while ((ss = input.read()) != -1) {
    79                         sb1.append((char) ss);
    80                     }
    81                     result = sb1.toString();
    82                     Log.e(TAG, "result : " + result);
    83                     return result;
    84                 } else {
    85                     Log.e(TAG, "request error");
    86                 }
    87             
    88             }
    89         } catch (MalformedURLException e) {
    90             e.printStackTrace();
    91         } catch (IOException e) {
    92             e.printStackTrace();
    93         }
    94         return null;
    95     }
    96 }

    3、编写activity.java

      1 public class UploadActivity extends BaseActivity implements OnItemSelectedListener,OnClickListener{
      2 
      3     private Button upload_btn;
      4 
      5     private ImageView img_view;
      6     private String imgv_path = "";
      7     private final String IMAGE_TYPE = "image/*";
      8     private final int IMAGE_CODE = 0;
      9         
     10     private Handler handler = new Handler();
     11 
     12     @Override
     13     protected void onCreate(Bundle savedInstanceState) {
     14         super.onCreate(savedInstanceState);
     15         requestWindowFeature(Window.FEATURE_NO_TITLE);
     16         setContentView(R.layout.uploadImage);
     17     
     18         img_view = (ImageView) findViewById(R.id.img_view);        
     19         upload_btn = (Button) findViewById(R.id.upload_btn);
     20         upload_btn.setOnClickListener(this);
     21 
     22     }    
     23 
     24     @Override
     25     public void onClick(View v) {
     26         switch (v.getId()) {    
     27         case R.id.upload_btn:
     28             selectImage();
     29             break;    
     30         default:
     31             break;
     32         }        
     33     }    
     34     
     35     @Override
     36     protected void onDestroy(){
     37         super.onDestroy();
     38     }
     39     
     40     /**
     41      * 选择上传图片
     42      * @param
     43      */
     44     private void selectImage() {
     45         Intent getAlbum = new Intent(Intent.ACTION_PICK);        
     46         getAlbum.setType(IMAGE_TYPE);
     47         startActivityForResult(getAlbum, IMAGE_CODE);
     48     }
     49 
     50     @Override
     51     protected void onActivityResult(int requestCode, int resultCode, Intent data) {
     52          if (requestCode == IMAGE_CODE) {
     53                 // 从相册返回的数据
     54                 if (data != null) {
     55                     // 得到图片的全路径
     56                     Uri uri = data.getData();
     57                     if (data != null) {
     58                          try {
     59                             // imgv_busicard.setImageBitmap(MediaStore.Images.Media.getBitmap(getContentResolver(), uri));
     60                              String[] proj = { MediaStore.Images.Media.DATA };
     61 
     62                              Cursor cursor = getContentResolver().query(uri, proj, null, null, null);
     63                              if (cursor.moveToFirst()) {
     64                                  int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
     65                                  String path = cursor.getString(column_index);
     66                                  uploadImage(path,MediaStore.Images.Media.getBitmap(getContentResolver(), uri));
     67                              }
     68                              cursor.close();
     69                         } catch (Exception e) {
     70                             // TODO Auto-generated catch block
     71                             e.printStackTrace();
     72                         }
     73                                      
     74                     }
     75                 }
     76          }
     77     }
     78     
     79     /**
     80      * 上传图片到服务器
     81      * @param requestCode
     82      * @param path
     83      */
     84 
     85     private void uploadImage(final String path,final Bitmap bmp) {
     86         final String url = HttpUtils.BASE_URL + "/uploadImage";
     87         final File file = new File(path);
     88         int fileLen = 0;
     89         try {
     90             FileInputStream fis = new FileInputStream(file);
     91             fileLen = fis.available();
     92         }catch (IOException e) {
     93             e.printStackTrace();
     94         }
     95         if (fileLen > 2 * 1024 * 1024) {
     96             DialogUtil.showDialog(UploadActivity.this, R.string.upload_oversize, false);
     97         } else {
     98             final String[] resultArr = {"",""};
     99             final Runnable runnableUI = new Runnable() {
    100                 @Override
    101                 public void run() {
    102                     if (Integer.valueOf(resultMsg) == 0) {
    103                         img_view.setImageBitmap(bmp);
    104                         imgv_path = "/upload/" + resultArr[0];                        
    105                     } else {
    106                         DialogUtil.showDialog(UploadActivity.this, resultArr[1], false);
    107                     }
    108                 }
    109             };
    110             new Thread() {
    111                 @Override
    112                 public void run() {
    113 
    114                     String result = HttpUtils.uploadFile(file, url);
    115 
    116                     try {
    117                         JSONObject json = new JSONObject(result);
    118                         resultMsg = json.get("error").toString();
    119                         resultArr[0] = json.get("src").toString();
    120                         resultArr[1] = json.get("message").toString();
    121                         handler.post(runnableUI);
    122                     } catch (JSONException e) {
    123                         e.printStackTrace();
    124                     }
    125                 }
    126             }.start();
    127     }
    128         
    129     }
    130 
    131 }

    4、服务器端接收客户端发来请求,本文采用jfinal框架,action如下

     1 public void uploadImage() {
     2         JSONObject json = new JSONObject();
     3         try {
     4             String path_date = CommonUtils.getCurrentTime();
     5             UploadFile uploadFile = getFile("image", "/" + path_date, 2 * 1024 * 1024, "utf-8"); // 最大上传20M的图片
     6             String fileName = uploadFile.getFileName();//getPara("filename");
     7             System.out.println(fileName);
     8             //fileName = fileName.substring(fileName.lastIndexOf("\") + 1); // 去掉路径
     9             File filePath = new File(PathKit.getWebRootPath() + "/temp/" + path_date);
    10             File source = new File(filePath + "/" + fileName); // 获取临时文件对象
    11             json.put("message", source.getAbsolutePath() + source.getName());
    12             String extension = fileName.substring(fileName.lastIndexOf("."));
    13             String savePath = PropKit.get("upload_path");
    14             
    15             extension = extension.toLowerCase();
    16             if (".png".equals(extension) || ".jpg".equals(extension) || ".gif".equals(extension)
    17                     || ".jpeg".equals(extension) || ".bmp".equals(extension)) {
    18 
    19                 FileInputStream fis = new FileInputStream(source);
    20 
    21                 File targetDir = new File(savePath);
    22                 if (!targetDir.exists()) {
    23                     targetDir.mkdirs();
    24                 }
    25                 fileName = Utils.generateRecordCode() + extension;// String.valueOf(apiResult.get("media_id"))
    26                                                                     // +
    27                                                                     // extension;
    28                 File target = new File(targetDir, fileName);
    29                 if (!target.exists()) {
    30                     target.createNewFile();
    31                 }
    32 
    33                 FileOutputStream fos = new FileOutputStream(target);
    34                 byte[] bts = new byte[1024 * 20];
    35                 while (fis.read(bts, 0, 1024 * 20) != -1) {
    36                     fos.write(bts, 0, 1024 * 20);
    37                 }
    38 
    39                 fos.close();
    40                 fis.close();
    41                 json.put("error", 0);
    42                 json.put("src", fileName); // 相对地址,显示图片用
    43                 source.delete();
    44 
    45             } else {
    46                 source.delete();
    47                 json.put("error", 1);
    48                 json.put("message", "只允许上传png,jpg,jpeg,gif类型的图片文件");
    49             }
    50         } catch (FileNotFoundException e) {
    51             json.put("error", 1);
    52             json.put("message", "上传出现错误,请稍后再上传");
    53         } catch (IOException e) {
    54             json.put("error", 1);
    55             json.put("message", "文件写入服务器出现错误,请稍后再上传");
    56         } catch(RuntimeException e){
    57             if(e.getMessage().contains("content length of")){
    58                 json.put("error", 1);
    59                 json.put("message", "图片不能大于2M");
    60             }else{                
    61                 json.put("error", 1);
    62                 json.put("message", e.getMessage());
    63             }
    64         }
    65         setRender(new JsonRender(json.toJSONString()).forIE());
    66     }
  • 相关阅读:
    mysql查看进程
    mysql case, if
    centos升级python2.7
    centos多版本python安装pip
    Python library not found: libpython2.7mu.so.1.0
    pip cannot confirm SSL certificate: SSL module is not available
    python: no module named bz2
    summary
    python生成可执行文件保护源码
    mysql 存储过程
  • 原文地址:https://www.cnblogs.com/Youngly/p/6108930.html
Copyright © 2020-2023  润新知