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

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. MFC 创建多层目录

    创建多层目录 BOOL CTestToolCtr::CreateFolder(CString strNewFolder) { /************************************ ...

  2. opencv计算运行时间

    double Time = (double)cvGetTickCount();//  算法过程Time = (double)cvGetTickCount() - Time ; printf( &quo ...

  3. PHPExcel 大数据的导出

    PHPExcel 是一个php语言读取导出数据.导入生成Excel的类库,使用起来非常方便,但有时会遇到以些问题,比如导出的数据超时,内存溢出等. 下面我们来说说这些问题和解决办法. PHPExcel ...

  4. [MS SQL Server]SQL Server如何开启远程访问

    在日常工作中,经常需要连接到远程的MS SQL Server数据库中.当然也经常会出现下面的连接错误. 解决方法: 1. 设置数据库允许远程连接,数据库实例名-->右键--->属性---C ...

  5. 1 Maximum Product Subarray_Leetcode

    Find the contiguous subarray within an array (containing at least one number) which has the largest ...

  6. MySQL深度巡检

    1. IO层面检查   (1)IO检查   查看%util是否接近100%定位是哪个磁盘IO压力大 #iostat -x 1 10 (2)iotop定位负载来源进程 查看哪个PID占用IO最高 #io ...

  7. 如何使用android百度地图离线地图

    1.首先把离线地图放在android工程下的assets里面. 注意:建议离线地图下载通过百度地图APIDEMO去下载,因为到官网上下载的离线地图文件格式不一样,APIDEMO的格式是.dat,而官网 ...

  8. Effective C++ 笔记1

    条款1:视C++为一个语言联邦 1.C.Object-Oriented C++.Template C++ .STL 组成了C++,高效编程取决你使用C++的哪一部分 条款2:尽量用const ,enu ...

  9. php js数组问题

    <script type="text/javascript"> var a = new Array(); a = "a"; a = "b& ...

  10. React Native MAC上环境搭建笔记

    今天花了一点时间搭建了一下react native环境,在这个过程中遇到了一些问题,处理并总结一下,年纪大了记性不好,只能多写写...真是岁月不饶人啊! 第一步:安装最新版本的Xcode工具 第二步: ...