上传图片或文件到服务器端
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了上传图片或文件到服务器端相关的知识,希望对你有一定的参考价值。
新建一个线程:
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;} } } }
以上是关于上传图片或文件到服务器端的主要内容,如果未能解决你的问题,请参考以下文章