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

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. js如何求一组数中的极值

    这是一个很简单的问题,现在我们从循环开始,例如一组数[5,2,1,3,4];求其中的最大值,那么首先我们要定义一个max的中间变量,遍历数组,当遇到比max值大则赋值给max,直到循环结束,就能获取这 ...

  2. HAProxy的安装与使用

    在互联网时代中,后台系统架构,经常可以听到高可用集群.负载均衡集群之类的系统架构解决方案,其中,负载均衡有基于硬件的F5.Big-IP等,也有基于软件的LVS(基于Linux操作系统实现,性能可以和基 ...

  3. while用法一例

    package com.chongrui.test;/*while用法一例 * *///import java.util.Scanner;public class TypeConvertion { p ...

  4. 1280*720P和1920*1080P的视频在25帧30帧50帧60帧时的参数

  5. 【Java EE 学习 78 上】【数据采集系统第十天】【Service使用Spring缓存模块】

    一.需求分析 调查问卷中或许每一个单击动作都会引发大量的数据库访问,特别是在参与调查的过程中,只是单击“上一页”或者“下一页”的按钮就会引发大量的查询,必须对这种问题进行优化才行.使用缓存策略进行查询 ...

  6. Officel常用操作

    Excel: 1.隔行变色|菜单->条件格式->其它规则->使用公式->"=MOD(ROW(),2)=0" 2.查找包含特定字符的单元格,并替换整个单元格 ...

  7. 关于安装Apache之后,解析PHP的配置

    需要配置四个地方 LoadModule php5_module modules/libphp5.soServerName localhost:80DirectoryIndex index.phpAdd ...

  8. 当DevOps撞上物联网

    DevOps 领域在近年来变得流行而普遍.它强调不同的角色之间共同协作,以及如何工作得更加紧密,就像这个词语的词根暗示的那样--开发和运维.但是DevOps和物联网有什么关系? 本文选自<Dev ...

  9. WEB开发入门

    对服务器的概念需要更新一下: 从物理上来说,服务器就是一台PC机,至少8核,以T计算,带宽100M以上 一般有的服务器 1. web服务器 -- PC机上安装一个具有web服务的软件 2. 数据库服务 ...

  10. SilverLight CheckBox 控件 DataContext属性与DataContextChanged事件

    当CheckBox对象创建时,会触发一次DataContextChanged事件,默认值待定,销毁时不会触发,代码修改DataContext时也会触发