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

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();
    }
}
 其余只需要 添加权限即可

希望能帮助你们

Android+jsp +html 文件上传案例 已测试 成功通过的更多相关文章

  1. Java实现一个简单的文件上传案例

    Java实现一个简单的文件上传案例 实现流程: 1.客户端从硬盘读取文件数据到程序中 2.客户端输出流,写出文件到服务端 3.服务端输出流,读取文件数据到服务端中 4.输出流,写出文件数据到服务器硬盘 ...

  2. TCP通信---文件上传案例、多线程文件上传

    目前大多数服务器都会提供文件上传的功能,由于文件上传需要数据的安全性和完整性,很明显需要使用TCP协议来实现. TCP通信需要创建一个服务器端程序和一个客户端程序,实现客户端向服务器端上传文件 代码实 ...

  3. web端、android端的文件上传

    1.web端的文件上传. 这里是利用了第三方的jar包.这里所需要的jar包我已经上传到本博客的资源里了,以下是连接 http://download.csdn.net/detail/caihongsh ...

  4. jsp Servlet 文件上传

    <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding= ...

  5. JSP多文件上传到服务器

    问题描述: 作为一个Java开发Web方向的程序员,很重要的一个功能,就是上传文件功能是一定要掌握的,今天整理了一下代码. 1.JSP显示界面代码和动态添加上传文件个数. <%@ page la ...

  6. 基于jsp的文件上传和下载

    参考: 一.JavaWeb学习总结(五十)--文件上传和下载 此文极好,不过有几点要注意: 1.直接按照作者的代码极有可能listfile.jsp文件中 <%@taglib prefix=&qu ...

  7. jsp简易文件上传(common.fileupload)

    昨天开始重新架构我的V&View(维视),之前写文章使用的是一个kindediter的插件,挺好用的.最近不知道咋了,出现了些小问题.早在写V&View的时候就想用以下两种方法实现文章 ...

  8. jsp实现文件上传下载

    文件上传: upload.jsp <form action="uploadServlet" method="post" enctype="mul ...

  9. 使用jsp实现文件上传的功能

    首先是表单的jsp文件:upload.jsp <%@ page contentType="text/html;charset=UTF-8" language="ja ...

随机推荐

  1. spring加载过程,源码带你理解从初始化到bean注入

    spring在容器启动时,容器正式初始化入口refresh()如下图 ①包括初始化FactoryBean.解析XML注册所有BeanDefinition信息  ②包括注册scope管理类  ③初始化单 ...

  2. JAVA 中配置IKAnalyzer扩展词库和停止词库

    1.后缀名.dic的词典文件,必须如使用文档里所说的 无BOM的UTF-8编码保存的文件.如果不确定什么是 无BOM的UTF-8编码,最简单的方式就是 用Notepad++编辑器打开,Encoding ...

  3. 同感,C#对JSON序列化和反序列化有点蹩脚

    http://www.cnblogs.com/baisoft/p/5860676.html

  4. 微信JS SDK配置授权,实现分享接口

    微信开放的JS-SDK面向网页开发者提供了基于微信内的网页开发工具包,最直接的好处就是我们可以使用微信分享.扫一扫.卡券.支付等微信特有的能力.7月份的时候,因为这个分享的证书获取问题深深的栽了一坑, ...

  5. Delphi容器类之---TList、TObjectList、TComponentList、TClassList

    转载自:http://blog.csdn.net/iseekcode/article/details/4922001 从Delphi5开始VCL中增加了新的Contnrs单元,单元中定义了8个新的类, ...

  6. c#中ObservableCollection<T>排序方法

    之前用到的一段代码,记录一下 public static class ObservableExtension { public static void Sort<TSource, TKey> ...

  7. AVL树的平衡算法(JAVA实现)

      1.概念: AVL树本质上还是一个二叉搜索树,不过比二叉搜索树多了一个平衡条件:每个节点的左右子树的高度差不大于1. 二叉树的应用是为了弥补链表的查询效率问题,但是极端情况下,二叉搜索树会无限接近 ...

  8. 【Hibernate框架】关联映射(多对多关联映射)

    按着我们的总结行进计划,接下来,就是有关于多对多映射的总结了. 我们来举个例子啊,很长时间以来,房价暴涨不落,但是还有很多人拥有很多套房产,假如说,一个富豪拥有九套房产,家里人么准去住哪一套,我们就以 ...

  9. Spring集成JUnit测试

    1.程序中有Junit环境2.导入一个jar包.spring与junit整合jar包 spring-test-3.2.0.RELEASE.jar3.测试代码 @RunWith(SpringJUnit4 ...

  10. 详细讲述MySQL中的子查询操作 (来自脚本之家)

    继续做以下的前期准备工作: 新建一个测试数据库TestDB: ? 1 create database TestDB; 创建测试表table1和table2: ? 1 2 3 4 5 6 7 8 9 1 ...