上傳圖片或文件到服務器端


新建一個線程:

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 }
View Code
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 }
View Code

 



服務器端文件:
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;}
        }

    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM