首页 > 其他分享 >android上传图片至服务器

android上传图片至服务器

时间:2023-04-30 11:03:34浏览次数:36  
标签:String new 服务器 android con 上传 ds name


本实例实现了android上传手机图片至服务器,服务器进行保存



服务器servlet代码
publicvoid doPost(HttpServletRequest request, HttpServletResponse response)  

           throws ServletException, IOException {  


           String temp=request.getSession().getServletContext().getRealPath("/")+"temp";   //临时目录
           System.out.println("temp="+temp);

           String loadpath=request.getSession().getServletContext().getRealPath("/")+"Image"; //上传文件存放目录
           System.out.println("loadpath="+loadpath);

           DiskFileUpload fu =new DiskFileUpload();

           fu.setSizeMax(1*1024*1024);   // 设置允许用户上传文件大小,单位:字节
           fu.setSizeThreshold(4096);   // 设置最多只允许在内存中存储的数据,单位:字节
           fu.setRepositoryPath(temp); // 设置一旦文件大小超过getSizeThreshold()的值时数据存放在硬盘的目录

//开始读取上传信息
int index=0;

           List fileItems =null;


try {

                                        fileItems = fu.parseRequest(request);

                                         System.out.println("fileItems="+fileItems);

                                } catch (Exception e) {

                                        e.printStackTrace();

                                }



           Iterator iter = fileItems.iterator(); // 依次处理每个上传的文件
while (iter.hasNext())

           {

               FileItem item = (FileItem)iter.next();// 忽略其他不是文件域的所有表单信息
if (!item.isFormField())

               {

                   String name = item.getName();//获取上传文件名,包括路径
                   name=name.substring(name.lastIndexOf("\\")+1);//从全路径中提取文件名
long size = item.getSize();
if((name==null||name.equals("")) && size==0)
continue;
int point = name.indexOf(".");

                   name=(new Date()).getTime()+name.substring(point,name.length())+index;

                   index++;

                   File fNew=new File(loadpath, name);
try {

                                        item.write(fNew);

                                } catch (Exception e) {
// TODO Auto-generated catch block
                                        e.printStackTrace();

                                }



               }
else//取出不是文件域的所有表单信息
               {

                   String fieldvalue = item.getString();
//如果包含中文应写为:(转为UTF-8编码)
//String fieldvalue = new String(item.getString().getBytes(),"UTF-8");
               }

           }

           String text1="11";

           response.sendRedirect("result.jsp?text1="+ text1);

    }


android客户端代码


publicclass PhotoUpload extends Activity {
private String newName ="image.jpg";
private String uploadFile ="/sdcard/image.JPG";
private String actionUrl ="http://192.168.0.71:8086/HelloWord/myForm";
private TextView mText1;
private TextView mText2;
private Button mButton;

    @Override
publicvoid onCreate(Bundle savedInstanceState)

      {
super.onCreate(savedInstanceState);

        setContentView(R.layout.photo_upload);

        mText1 = (TextView) findViewById(R.id.myText2);
//"文件路径:\n"+
        mText1.setText(uploadFile);

        mText2 = (TextView) findViewById(R.id.myText3);
//"上传网址:\n"+
        mText2.setText(actionUrl);


        mButton = (Button) findViewById(R.id.myButton);

        mButton.setOnClickListener(new View.OnClickListener()

        {
publicvoid onClick(View v)

          {

            uploadFile();

          }

        });

      }

privatevoid uploadFile()

      {

        String end ="\r\n";

        String twoHyphens ="--";

        String boundary ="*****";
try

        {

          URL url =new URL(actionUrl);

          HttpURLConnection con=(HttpURLConnection)url.openConnection();


          con.setDoInput(true);

          con.setDoOutput(true);

          con.setUseCaches(false);


          con.setRequestMethod("POST");


          con.setRequestProperty("Connection", "Keep-Alive");

          con.setRequestProperty("Charset", "UTF-8");

          con.setRequestProperty("Content-Type",

                             "multipart/form-data;boundary="+boundary);


          DataOutputStream ds =
new DataOutputStream(con.getOutputStream());

          ds.writeBytes(twoHyphens + boundary + end);

          ds.writeBytes("Content-Disposition: form-data; "+

                        "name=\"file1\";filename=\""+

                        newName +"\""+ end);

          ds.writeBytes(end);  


          FileInputStream fStream =new FileInputStream(uploadFile);

int bufferSize =1024;
byte[] buffer =newbyte[bufferSize];
int length =-1;

while((length = fStream.read(buffer)) !=-1)

          {


            ds.write(buffer, 0, length);

          }

          ds.writeBytes(end);

          ds.writeBytes(twoHyphens + boundary + twoHyphens + end);


          fStream.close();

          ds.flush();


          InputStream is = con.getInputStream();
int ch;

          StringBuffer b =new StringBuffer();
while( ( ch = is.read() ) !=-1 )

          {

            b.append( (char)ch );

          }


          showDialog("上传成功"+b.toString().trim());


          ds.close();

        }
catch(Exception e)

        {

          showDialog("上传失败"+e);

        }

      }

privatevoid showDialog(String mess)

      {
new AlertDialog.Builder(PhotoUpload.this).setTitle("Message")

         .setMessage(mess)

         .setNegativeButton("确定",new DialogInterface.OnClickListener()

         {
publicvoid onClick(DialogInterface dialog, int which)

           {          

           }

         })

         .show();

      }

    }

标签:String,new,服务器,android,con,上传,ds,name
From: https://blog.51cto.com/u_548275/6237794

相关文章

  • Android 开发 UI 规则
    Android的官方开发者博客发了一份幻灯片,介绍了一些AndroidUI设计的小贴士,在这里以看图说话的形式发出来。Don’t: 1、不要照搬你在其它平台的UI设计,应该让用户感觉是在真正使用一个Android软件,在你的商标显示和平台整体观感之间做好平衡2、不要过度使用模态对话框3、......
  • Android应用程序的国际化与本地化
    internationalization(国际化)简称i18n,因为在i和n之间还有18个字符,localization(本地化),简称L10n。 zh_CN,zh_TW. http://www.loc.gov/standards/iso639-2/php/code_list.phphttp://www.iso.org/iso/en/prods-services/iso3166ma/02iso-3166-code-lists/list-en1.html在Andro......
  • android中的像素单位dp、px、pt、s…
    pixels(设备独立像素).不同设备有不同的显示效果,这个和设备硬件有关,一般我们为了支持WVGA、HVGA和QVGA推荐使用这个,不依赖像素。px:pixels(像素).不同设备显示效果相同,一般我们HVGA代表320x480像素,这个用的比较多。pt:point,是一个标准的长度单位,1pt=1/72英寸,用于......
  • android中退出当前应用程序的四种…
    Android程序有很多Activity,比如说主窗口A,调用了子窗口B,如果在B中直接finish(),接下里显示的是A。在B中如何关闭整个Android应用程序呢?本人总结了几种比较简单的实现方法。1.DalvikVM的本地方法android.os.Process.killProcess(android.os.Process.myPid())//获取PID......
  • android TextView属性大全
    android:autoLink设置是否当文本为URL链接/email/电话号码/map时,文本显示为可点击的链接。可选值(none/web/email/phone/map/all)android:autoText如果设置,将自动执行输入值的拼写纠正。此处无效果,在显示输入法并输入的时候起作用。android:bufferType指定get......
  • Android Bitmap内存溢出问题解释
    Android平台在图片处理方面经常会出现OOM的问题,在去年开发的一个项目中,我也一直被这个问题所困扰,在这方面也搜集了许多的资料,今天仅仅针对Android平台的Bitmap说事儿,今后再对内存的问题做详细的探讨,android平台对图片解码这块确实设置的有内存上限,在解码Bitmap的时候android平台会......
  • Android开发中立即停止AsyncTask和…
    程序开发中经常会有立即停止线程运行的需要,而通过api是没有办法实现这个目的的,因此对于这个情况,我们需要采取一些“特殊”的方式来实现:  1,判断标志位的办法:  我们要知道在java的线程中,没有办法停止一个正在运行中的线程。在Android的AsyncTask中也是一样的。如果必须要停......
  • android上传base64的字符图片
    一般来说,目前在手机端上传图片,方法挺多的,不过常用的就是一个文件流,另一个是二进制转base64的字符流,下面分享一下方法网络上都是千篇一律的写法,对于上传过程中失败的问题也很少提及,上传失败的bug,主要的原因当然是编码字符的问题了,一般网上都没有介绍,记得要将base64的字符串转......
  • Android 用户界面---样式和主…
    样式是给View或Window指定外观和格式的属性集合。样式能够指定如高、边距、字体颜色、字体尺寸、背景颜色等属性。样式被定义在一个与布局XML文件分开的XML资源文件中。Android中的样式与Web设计中的层叠式样表类似,允许与内容分开设计。例如,通过使用样式,可以把下面这个布局XML转换......
  • Android应用程序的安装位置(二)
    不应该安装在外部存储器上的应用程序当用户启用USB存储器来跟计算机共享文件时(或者是卸载或移除外部存储器),任何被安装在外部存储器上,并且当前正在运行的应用程序都会被杀死。在USB存储器被禁用和外部存储器被重新挂载到设备上之前,系统不会有效的感知到引用程序的存在。除了终止应......