服务器端 (可直接把我的一些自定义的东西去掉,例如JsonData,Log4netHelper什么的,换成你自己所需要的)
//HomeController.cs
public ActionResult UploadImage(HttpPostedFileBase file)
{}
//加上这个则可以让手机端下载的图片缓存在手机中,使用volley就可以在无网络的时候直接拿到缓存中数据
[OutputCache(Duration = 3600000)]
public FileStreamResult GetFileFromDisk()
{
string path = AppDomain.CurrentDomain.BaseDirectory + "/../";
string fileName = "forest.jpg";
return File(new FileStream(path + fileName, FileMode.Open), "image/jpeg", fileName);
}
手机端
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == R.id.btLogin) {
new Thread(new Runnable() {
public void run() {
try{
Bitmap bitmap = BitmapFactory.decodeResource(LoginActivity.this.getApplicationContext().getResources(), R.drawable.ic_launcher);
String http = "http://192.168.1.113:8080/Home/UploadImage/";
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(http);
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 75, bos);
byte[] data = bos.toByteArray();
ByteArrayBody bab = new ByteArrayBody(data, "forest.jpg");
//这里的第一个参数要和服务器的参数名一样
reqEntity.addPart("file", bab);
// File ff = Environment.getExternalStorageDirectory();
// String rootAndName = ff.getPath()+"/ludashi_weibo_img.jpg";
// File file = new File(rootAndName);
// reqEntity.addPart("file", new FileBody(file));
postRequest.setEntity(reqEntity);
HttpResponse response = httpClient.execute(postRequest);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String sResponse;
StringBuilder s = new StringBuilder();
while ((sResponse = reader.readLine()) != null) {
s = s.append(sResponse);
}
Log.e("sss",s.toString());
}
catch(Exception e){
Log.e("Exception in Image", ""+e);
}
}
}).start();
}
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 如果已经登录,则直接进入主界面
setContentView(R.layout.activity_login);
initialWidget();
RequestQueue mQueue = Volley.newRequestQueue(getApplicationContext());
int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
BitmapCache ca = new BitmapCache(maxMemory,getApplicationContext());
ImageLoader imageLoader = new ImageLoader(mQueue, ca);
networkImageView.setDefaultImageResId(R.drawable.ic_launcher);
networkImageView.setErrorImageResId(R.drawable.ic_launcher);
String imageURL = "http://192.168.1.113:8080/Home/GetFileFromDisk";
));
networkImageView.setImageUrl(imageURL,
imageLoader);
}