Android+jsp +html 文件上传案例 已测试 成功通过

我文件上传一直是广大读者一个问题 今天就把成功案例写下

javaweb

网页前段

<%@ page language="java" import="java.util.*" pageEncoding="Utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
  </head>
 
  <body>
  <form id="form1" name="form1" method="post" action="servlet/upload" enctype="multipart/form-data">
 <table border="0" align="center">
  <tr>
   <td>上传人:</td>
   <td>
    <input name="name" type="text" id="name" size="20" ></td>
  </tr>  
  <tr>
   <td>上传文件:</td>
   <td><input name="file" type="file" size="20" ></td>
  </tr>    
  <tr>   
   <td></td><td>
    <input type="submit" name="submit" value="提交" >
    <input type="reset" name="reset" value="重置" >
   </td>
  </tr>
 </table>
</form>
  </body>
</html>
服务器后端

代码建议一个Servlet之前需要下载commons-fileupload-1.2.2.jar,commons-io-2.0.1.jar 架包

建议servlet 名字是upload

期待代码如下

package com.example.wenjian;

import java.io.File;

import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity {
private Button button,button2;
private EditText editText;
private String picpath;
private ImageView imageView;
private String text;
private String url="http://10.17.151.66:8080/upload/servlet/upload";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    button=(Button)this.findViewById(R.id.button1);
    button2=(Button)this.findViewById(R.id.button2);
    imageView=(ImageView)this.findViewById(R.id.imageview);
    button.setOnClickListener(new OnClickListener() {
        
        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
//             Intent intent = new Intent();
//                intent.setType("image/*");
//                intent.setAction(Intent.ACTION_GET_CONTENT);
//                startActivityForResult(intent, 1);
                Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);  
                startActivityForResult(intent, 1);  
             
        }
    });
    button2.setOnClickListener(new OnClickListener() {
        
        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            
        final File file=new File(picpath);
        if(file!=null){    
            new Thread(){
                public void run() {
                     text=    UploadUtil.uploadFile(file, url);
//                    uploadimage uploadimage=new uploadimage();
//                    String text=uploadimage.uploadFile(url, "image.jpg", file);
                    Message message=Message.obtain();
                    message.what=1;
                    message.obj=text;
                    System.out.println("------text"+text);
                    handler.sendMessage(message);
//                Toast.makeText(MainActivity.this, text, 1).show();
                
                };
            }.start();
        
        }
        }
    });
    }
private Handler handler=new Handler(){
    public void handleMessage(Message msg) {
        if (msg!=null) {
            if(msg.what==1){
                 text=(String) msg.obj;
                Toast.makeText(MainActivity.this, text, 1).show();
            }
            
        }
    };
};

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            // TODO Auto-generated method stub
        if(requestCode == 1 && resultCode == RESULT_OK && data != null){
//            if(requestCode==Activity.RESULT_OK){
            Uri uri=data.getData();
            System.out.println("---uri"+uri);
            try {
                String[] pojo={MediaStore.Images.Media.DATA};
                Cursor cursor=managedQuery(uri, pojo,
                        null, null, null);
                if(cursor!=null){
                    System.out.println("-------hahaha");
                    ContentResolver cr=this.getContentResolver();
                    int colunm_index=cursor.getColumnIndexOrThrow(
MediaStore.Images.Media.DATA);
                    cursor.moveToFirst();
                    String path=cursor.getString(colunm_index);
                    System.out.println("----"+path);
                    if(path.endsWith("jpg")||path.endsWith("png")){
                        picpath=path;
                        Bitmap bitmap=BitmapFactory.decodeStream(
                                cr.openInputStream(uri));
                        imageView.setImageBitmap(bitmap);
                    }else {
                        alert();
                    }
                }else {
                    alert();
                }
                        
            } catch (Exception e) {
                // TODO: handle exception
            }
        }
        
            super.onActivityResult(requestCode, resultCode, data);
        }
    private void alert()
    {
        Dialog dialog = new AlertDialog.Builder(this)
        .setTitle("提示")
        .setMessage("您选择的不是有效的图片")
        .setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,
                            int which) {
                        picpath = null;
                    }
                })
        .create();
        dialog.show();
    }
}
 Android端代码

网页客户端前台

布局 如下

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

 
<ImageView  android:layout_width="fill_parent"
    android:layout_height="200sp"
    android:id="@+id/imageview"
    android:src="@drawable/ic_launcher"/>
    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="选择图片" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="上传图片" />

</LinearLayout>

Android 端逻辑代码如下

package com.example.wenjian;

import java.io.File;

import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity {
private Button button,button2;
private EditText editText;
private String picpath;
private ImageView imageView;
private String text;
private String url="http://10.17.151.66:8080/upload/servlet/upload";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    button=(Button)this.findViewById(R.id.button1);
    button2=(Button)this.findViewById(R.id.button2);
    imageView=(ImageView)this.findViewById(R.id.imageview);
    button.setOnClickListener(new OnClickListener() {
        
        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
//             Intent intent = new Intent();
//                intent.setType("image/*");
//                intent.setAction(Intent.ACTION_GET_CONTENT);
//                startActivityForResult(intent, 1);
                Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);  
                startActivityForResult(intent, 1);  
             
        }
    });
    button2.setOnClickListener(new OnClickListener() {
        
        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            
        final File file=new File(picpath);
        if(file!=null){    
            new Thread(){
                public void run() {
                     text=    UploadUtil.uploadFile(file, url);
//                    uploadimage uploadimage=new uploadimage();
//                    String text=uploadimage.uploadFile(url, "image.jpg", file);
                    Message message=Message.obtain();
                    message.what=1;
                    message.obj=text;
                    System.out.println("------text"+text);
                    handler.sendMessage(message);
//                Toast.makeText(MainActivity.this, text, 1).show();
                
                };
            }.start();
        
        }
        }
    });
    }
private Handler handler=new Handler(){
    public void handleMessage(Message msg) {
        if (msg!=null) {
            if(msg.what==1){
                 text=(String) msg.obj;
                Toast.makeText(MainActivity.this, text, 1).show();
            }
            
        }
    };
};

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            // TODO Auto-generated method stub
        if(requestCode == 1 && resultCode == RESULT_OK && data != null){
//            if(requestCode==Activity.RESULT_OK){
            Uri uri=data.getData();
            System.out.println("---uri"+uri);
            try {
                String[] pojo={MediaStore.Images.Media.DATA};
                Cursor cursor=managedQuery(uri, pojo,
                        null, null, null);
                if(cursor!=null){
                    System.out.println("-------hahaha");
                    ContentResolver cr=this.getContentResolver();
                    int colunm_index=cursor.getColumnIndexOrThrow(
MediaStore.Images.Media.DATA);
                    cursor.moveToFirst();
                    String path=cursor.getString(colunm_index);
                    System.out.println("----"+path);
                    if(path.endsWith("jpg")||path.endsWith("png")){
                        picpath=path;
                        Bitmap bitmap=BitmapFactory.decodeStream(
                                cr.openInputStream(uri));
                        imageView.setImageBitmap(bitmap);
                    }else {
                        alert();
                    }
                }else {
                    alert();
                }
                        
            } catch (Exception e) {
                // TODO: handle exception
            }
        }
        
            super.onActivityResult(requestCode, resultCode, data);
        }
    private void alert()
    {
        Dialog dialog = new AlertDialog.Builder(this)
        .setTitle("提示")
        .setMessage("您选择的不是有效的图片")
        .setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,
                            int which) {
                        picpath = null;
                    }
                })
        .create();
        dialog.show();
    }
}
 其余只需要 添加权限即可

希望能帮助你们

 

转载于:https://www.cnblogs.com/chengfanrong/p/4899076.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值