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

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. head标签详细讲解

    head标签详细讲解 head位于html网页的头部,后前的标签,并以开始以结束的一html标签. Head标签位置如图: head标签示意图 head包含标签 meta,title,link,bas ...

  2. Ubuntu 搭建SSH服务器

    参考地址:https://help.ubuntu.com/community/SSH/OpenSSH/Configuring 配置文件路径:/etc/ssh/ssh_config 和 /etc/ssh ...

  3. IIS设置默认主页无效

    服务器系统:Windows server 2008 R2 IIS版本:7.5 IIS中部署一个dotnet framework 3.5的网站应用程序,设置"默认文档"为:index ...

  4. Linux下免安装版sublime text 3显示图标

    执行如下命令 sudo vim /usr/share/applications/sublime_text_3.desktop 根据个人存放位置添加如下内容信息: [Desktop Entry] Enc ...

  5. pyqt的信号槽机制(转)

    PySide/PyQt Tutorial: Creating Your Own Signals and Slots This article is part 5 of 8 in the series  ...

  6. AudioSpecificConfig

    2个字节. 下面蓝色的为AudioSpecificConfig部分: 000001e0h: 00 00 00 00 00 AF 0011 90 00 00 00 0F 09 00 02; .....? ...

  7. Servlet读取Excel标准化数据库过程记录

    完成数据库的连接 获取连接参数 拷贝1.数据库URL 2.驱动程序类 3.用户 编写Servlet 1.创建连接对象 Connection con = null; PreparedStatement ...

  8. css/js(工作中遇到的问题)-4

    JS生成随机的由字母数字组合的字符串 Math.random().toString(36).substr(2)

  9. adt_sdk_tools介绍

    draw9patch.bat hierarchyviewer.bat traceview.bat

  10. 推荐Linux管理员不可不知十大PHP安全要点 - SCutePHP

    PHP是使用最广泛的脚本编程语言之一.市场份额颇能说明其主导地位.PHP 7已推出,这个事实让这种编程语言对当前的开发人员来说更具吸引力.尽管出现了一些变化,但是许多开发人员对PHP的未来持怀疑态度. ...