上传图片或文件到服务器端

新建一个线程:

new Thread(uploadImageRunnable).start();
Runnable uploadImageRunnable = new Runnable() {   @Override   public void run() {

      if(TextUtils.isEmpty(imgUrl)){         Toast.makeText(mContext, "还没有设置上传服务器的路径!", Toast.LENGTH_SHORT).show();         return;      }

      Map<String, String> textParams = new HashMap<String, String>();      Map<String, File> fileparams = new HashMap<String, File>();

      try {         // 创建一个URL对象         URL url = new URL(imgUrl);   //imageUrl指向服务器端文件         textParams = new HashMap<String, String>();         fileparams = new HashMap<String, File>();         // 要上传的图片文件         File file = new File(picPath);   //picPath为该图片或文件的uri         fileparams.put("image", file);         // 利用HttpURLConnection对象从网络中获取网页数据         HttpURLConnection conn = (HttpURLConnection) url.openConnection();         // 设置连接超时(记得设置连接超时,如果网络不好,Android系统在超过默认时间会收回资源中断操作)         conn.setConnectTimeout(5000);         // 设置允许输出(发送POST请求必须设置允许输出)         conn.setDoOutput(true);         // 设置使用POST的方式发送         conn.setRequestMethod("POST");         // 设置不使用缓存(容易出现问题)         conn.setUseCaches(false);         // 在开始用HttpURLConnection对象的setRequestProperty()设置,就是生成HTML文件头         conn.setRequestProperty("ser-Agent", "Fiddler");         // 设置contentType         conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + NetUtil.BOUNDARY);         OutputStream os = conn.getOutputStream();         DataOutputStream ds = new DataOutputStream(os);         NetUtil.writeStringParams(textParams, ds);         NetUtil.writeFileParams(fileparams, ds);         NetUtil.paramsEnd(ds);         // 对文件流操作完,要记得及时关闭         os.close();         // 服务器返回的响应吗         int code = conn.getResponseCode(); // 从Internet获取网页,发送请求,将网页以流的形式读回来         // 对响应码进行判断         if (code == 200) {// 返回的响应码200,是成功            // 得到网络返回的输入流            InputStream is = conn.getInputStream();            resultStr = NetUtil.readString(is);         } else {            Toast.makeText(mContext, "请求URL失败!", Toast.LENGTH_SHORT).show();         }      } catch (Exception e) {         e.printStackTrace();      }      handler.sendEmptyMessage(0);// 执行耗时的方法之后发送消给handler   }};
Handler handler = new Handler(new Handler.Callback() {    //返回在服务器端的uri

   @Override   public boolean handleMessage(Message msg) {      switch (msg.what) {         case 0:

            try {               JSONObject jsonObject = new JSONObject(resultStr);               // 服务端以字符串“1”作为操作成功标记               if (jsonObject.optString("status").equals("1")) {

                  // 用于拼接发布说说时用到的图片路径                  // 服务端返回的JsonObject对象中提取到图片的网络URL路径                  String imageUrl = jsonObject.optString("imageUrl");                  // 获取缓存中的图片路径                  Toast.makeText(mContext, imageUrl, Toast.LENGTH_SHORT).show();               } else {                  Toast.makeText(mContext, jsonObject.optString("statusMessage"), Toast.LENGTH_SHORT).show();               }

            } catch (JSONException e) {               e.printStackTrace();            }            break;         default:            break;      }      return false;   }});

NetUtil:

  1 package sun.geoffery.uploadpic;
  2
  3 import java.io.ByteArrayOutputStream;
  4 import java.io.DataOutputStream;
  5 import java.io.File;
  6 import java.io.FileInputStream;
  7 import java.io.InputStream;
  8 import java.net.URLEncoder;
  9 import java.util.Iterator;
 10 import java.util.Map;
 11 import java.util.Set;
 12
 13 public class NetUtil {
 14
 15     // 一般来说用一个生成一个UUID的话,会可靠很多,这里就不考虑这个了
 16     // 而且一般来说上传文件最好用BASE64进行编码,你只要用BASE64不用的符号就可以保证不冲突了。
 17     // 尤其是上传二进制文件时,其中很可能有\r、\n之类的控制字符,有时还可能出现最高位被错误处理的问题,所以必须进行编码。
 18     public static final String BOUNDARY = "--my_boundary--";
 19
 20     /**
 21      * 普通字符串数据
 22      * @param textParams
 23      * @param ds
 24      * @throws Exception
 25      */
 26     public static void writeStringParams(Map<String, String> textParams,
 27                                          DataOutputStream ds) throws Exception {
 28         Set<String> keySet = textParams.keySet();
 29         for (Iterator<String> it = keySet.iterator(); it.hasNext();) {
 30             String name = it.next();
 31             String value = textParams.get(name);
 32             ds.writeBytes("--" + BOUNDARY + "\r\n");
 33             ds.writeBytes("Content-Disposition: form-data; name=\"" + name + "\"\r\n");
 34             ds.writeBytes("\r\n");
 35             value = value + "\r\n";
 36             ds.write(value.getBytes());
 37
 38         }
 39     }
 40
 41     /**
 42      * 文件数据
 43      * @param fileparams
 44      * @param ds
 45      * @throws Exception
 46      */
 47     public static void writeFileParams(Map<String, File> fileparams,
 48                                        DataOutputStream ds) throws Exception {
 49         Set<String> keySet = fileparams.keySet();
 50         for (Iterator<String> it = keySet.iterator(); it.hasNext();) {
 51             String name = it.next();
 52             File value = fileparams.get(name);
 53             ds.writeBytes("--" + BOUNDARY + "\r\n");
 54             ds.writeBytes("Content-Disposition: form-data; name=\"" + name + "\"; filename=\""
 55                     + URLEncoder.encode(value.getName(), "UTF-8") + "\"\r\n");
 56             ds.writeBytes("Content-Type:application/octet-stream \r\n");
 57             ds.writeBytes("\r\n");
 58             ds.write(getBytes(value));
 59             ds.writeBytes("\r\n");
 60         }
 61     }
 62
 63     // 把文件转换成字节数组
 64     private static byte[] getBytes(File f) throws Exception {
 65         FileInputStream in = new FileInputStream(f);
 66         ByteArrayOutputStream out = new ByteArrayOutputStream();
 67         byte[] b = new byte[1024];
 68         int n;
 69         while ((n = in.read(b)) != -1) {
 70             out.write(b, 0, n);
 71         }
 72         in.close();
 73         return out.toByteArray();
 74     }
 75
 76     /**
 77      * 添加结尾数据
 78      * @param ds
 79      * @throws Exception
 80      */
 81     public static void paramsEnd(DataOutputStream ds) throws Exception {
 82         ds.writeBytes("--" + BOUNDARY + "--" + "\r\n");
 83         ds.writeBytes("\r\n");
 84     }
 85
 86     public static String readString(InputStream is) {
 87         return new String(readBytes(is));
 88     }
 89
 90     public static byte[] readBytes(InputStream is) {
 91         try {
 92             byte[] buffer = new byte[1024];
 93             int len = -1;
 94             ByteArrayOutputStream baos = new ByteArrayOutputStream();
 95             while ((len = is.read(buffer)) != -1) {
 96                 baos.write(buffer, 0, len);
 97             }
 98             baos.close();
 99             return baos.toByteArray();
100         } catch (Exception e) {
101             e.printStackTrace();
102         }
103         return null;
104     }
105
106 }

FileUtil:

 1 package sun.geoffery.uploadpic;
 2
 3 import java.io.ByteArrayOutputStream;
 4 import java.io.File;
 5 import java.io.FileOutputStream;
 6 import java.io.IOException;
 7 import java.text.SimpleDateFormat;
 8 import java.util.Date;
 9 import java.util.Locale;
10
11 import android.content.Context;
12 import android.graphics.Bitmap;
13 import android.graphics.Bitmap.CompressFormat;
14 import android.os.Environment;
15
16 public class FileUtil {
17
18     public static String saveFile(Context c, String fileName, Bitmap bitmap) {
19         return saveFile(c, "", fileName, bitmap);
20     }
21
22     public static String saveFile(Context c, String filePath, String fileName, Bitmap bitmap) {
23         byte[] bytes = bitmapToBytes(bitmap);
24         return saveFile(c, filePath, fileName, bytes);
25     }
26
27     public static byte[] bitmapToBytes(Bitmap bm) {
28         ByteArrayOutputStream baos = new ByteArrayOutputStream();
29         bm.compress(CompressFormat.JPEG, 100, baos);
30         return baos.toByteArray();
31     }
32
33     public static String saveFile(Context c, String filePath, String fileName, byte[] bytes) {
34         String fileFullName = "";
35         FileOutputStream fos = null;
36         String dateFolder = new SimpleDateFormat("yyyyMMdd", Locale.CHINA)
37                 .format(new Date());
38         try {
39             String suffix = "";
40             if (filePath == null || filePath.trim().length() == 0) {
41                 filePath = Environment.getExternalStorageDirectory() + "/JiaXT/" + dateFolder + "/";
42             }
43             File file = new File(filePath);
44             if (!file.exists()) {
45                 file.mkdirs();
46             }
47             File fullFile = new File(filePath, fileName + suffix);
48             fileFullName = fullFile.getPath();
49             fos = new FileOutputStream(new File(filePath, fileName + suffix));
50             fos.write(bytes);
51         } catch (Exception e) {
52             fileFullName = "";
53         } finally {
54             if (fos != null) {
55                 try {
56                     fos.close();
57                 } catch (IOException e) {
58                     fileFullName = "";
59                 }
60             }
61         }
62         return fileFullName;
63     }
64 }


服务器端文件:
using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data.OleDb;
using System.Drawing;
using System.Data;
using MySQLDriverCS;
using System.Web.Script.Serialization;
using System.Web.Http;
using System.Text;
using System.Data.SqlClient;

namespace JoinFun.Controllers
{
    public class UpLoadPictureController : Controller
    {
        //
        // GET: /UpLoadPicture/

        public String Index()
        {
            String userid = Request.Form["userid"];
            HttpPostedFileBase postfile = Request.Files["image"];
            String FileName = "D:\\JoinFun\\userpicture\\Userpicture" + userid + ".png";
            postfile.SaveAs(FileName);
            if (postfile != null)
            {
                String result = "{‘status‘:‘1‘,‘statusMessage‘:‘上传成功‘,‘imageUrl‘:‘http://......../JoinFunPicture/kenan.png‘}";
                return result;
            }
            else{
                String haha = "{‘status‘:‘1‘,‘statusMessage‘:‘上传成功‘,‘imageUrl‘:‘danteng‘}";
                return haha;}
        }

    }
}
时间: 2024-08-24 08:49:17

上传图片或文件到服务器端的相关文章

C# WinForm 上传图片,文件到服务器的方法Uploader.ashx

网上有很多方案,起初用时,因为对asp.net不太了解,觉得FTP实现不错,可是后来发现,如果机器在域控下,就会有问题. 一年过去了,asp.net也熟悉了,知道ajax没事应该用ashx,验证码也用ashx,当然这里要说的WinForm上传也应该是ashx了吧,哈哈,先提供简单思路: 接收文件的asp.net是:Uploader.ashx,相关代码: view plaincopy to clipboardprint? <%@ WebHandler Language="C#" C

TCP编程例三:从客户端发送文件给服务器端,服务器端保存到本地,并返回“发送成功”给客户端。

import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.InetAddress; import java.

解决selenium自动化上传图片或文件出现windows窗口问题

在实际工作中,会经常遇到上传图片或文件的操作,有的是input标签的,有的是非input标签属性的.他们都有一个共同的特性会出现windows的弹出窗. 下面说下出现windows的弹出窗后怎么解决:总共2个步骤 1,首先点击打开,待出现选择文件的弹出窗后: 2,调用我下面这个函数: 提示:调用此方法需要在打开windows上传文件的系统窗口后再调用 (该方法适用于谷歌驱动) '''实现非input标签上传文件,调用此方法需要打开windows上传文件的系统窗口再调用''' import win

关于Asp.Net Mvc3.0 使用KindEditor4.0 上传图片与文件

http://blog.csdn.net/fyxq14hao/article/details/7245502 今天我们的Asp.Net Mvc 3的项目中,把KindEditor3.9改为 KindEditor4.0 .修改了js文件的引用后,发现还是无法上传图片,最后发现时图片上传中的参数名修改了  从imageUploadJson 改为了uploadJson. <script type="text/javascript">var editor;var options =

Ueditor 1.4.3 单独调用上传图片,或文件功能

第一步, 引入文件 <script src="ueditor/ueditor.config.js" type="text/javascript" charset="utf-8"></script> <script src="ueditor/ueditor.all.min.js" type="text/javascript" charset="utf-8"&g

在.net MVC中异步上传图片或者文件

今天用到了MVC异步上传图片,找了半天写下来以后方便查找异步提交图片需要一个MyAjaxForm.cs             地址http://pan.baidu.com/s/1i3lA693 密码txgp 前台代码 @using (Ajax.BeginForm("AddMessages", "MenuInfo", new AjaxOptions { HttpMethod = "post", OnSuccess = "Successd

android使用wcf接收上传图片视频文件

一.Android 权限配置文件: <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.niewei.updatefile" android:versionCode="1" android:versio

上传图片或者文件

以后绝对会用到  使用ajax上传文件或者图片 urls: from django.contrib import admin from django.urls import path from one import views urlpatterns = [ path('admin/', admin.site.urls), path('upload_img/',views.upload_img), #上传图片 path('form_data_upload/',views.form_data_up

python测试开发django-47.xadmin上传图片和文件

前言 xadmin上传图片和上传文件功能 models模块设计 先设计一个model,用ImageField存放图片,FileField放文件,upload_to参数是存放的目录 # models.py from django.db import models from django.utils import timezone # Create your models here. class FileImage(models.Model): '''上传文件和图片''' title = model