using System; using System.Collections.Generic; using System.Diagnostics; using System.Drawing; using System.EnterpriseServices; using System.IO; using System.Linq; using System.Net; using System.Runtime.Serialization.Json; using System.ServiceModel; using System.ServiceModel.Activation; using System.ServiceModel.Web; using System.Threading.Tasks; using System.Web; namespace Comit.Vehicle.RestAgentServices { [ServiceContract, AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] [ServiceBehavior(IncludeExceptionDetailInFaults = true)] [GlobalExceptionHandlerBehaviour(typeof(GlobalExceptionHandler))] public class UploadServices { /// <summary> /// 上传图片 /// </summary> /// <param name="source"></param> /// <returns></returns> [WebInvoke(UriTemplate = "UploadImg", Method = "POST"), Description("上传图片")] public string UploadImg(Stream source) { var stopwatch = Stopwatch.StartNew(); //请求地址 string fileName = string.Empty; string serviceUrl = "UploadServices/UploadImg"; try { //获取HTTP请求头部集合 WebHeaderCollection headerCollection = WebOperationContext.Current.IncomingRequest.Headers; //业务编号 int um_id = int.Parse(headerCollection["UM_ID"]); //用户编号 int u_id = int.Parse(headerCollection["U_ID"]); string NAME = headerCollection["NAME"]; if (um_id > 0) { fileName = string.Format("{0}_{1}", DateTime.Now.ToString("yyyyMMddHHmmssffff"), NAME); string imageDir = System.Configuration.ConfigurationManager.AppSettings.Get("uploadImg"); string uploadPath = string.Format("{0}{1}",imageDir , u_id); //创建行程目录 if (!Directory.Exists(uploadPath)) Directory.CreateDirectory(uploadPath); //保存的物理路径 string dirpath = string.Format("{0}/{1}", uploadPath, fileName); //网站调用显示的的路径 UploadFile(source, dirpath); return "true"; } else { //throw new WebFaultException<M_ERROR>(ErrorHelper.SetErrorCode(M_ENUM_CODE.PARAM_ERROR, serviceUrl), HttpStatusCode.OK); return "false"; } } catch (Exception ex) { //Logger.Error(fileName + "图片上传出错", ex); return "false"; } finally { if (!string.IsNullOrEmpty(fileName)){ // Logger.Warn(string.Format("{0}图片上传完成,耗时{1:F1}秒", fileName, stopwatch.Elapsed.TotalSeconds)); } } } /// <summary> /// 上传文件 /// </summary> /// <param name="source">数据源</param> /// <param name="path">路径</param> private static void UploadFile(Stream source, string path) { Stream destination = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write); byte[] buffer = new byte[0x1000]; int numRead; while ((numRead = source.Read(buffer, 0, buffer.Length)) > 0) { destination.Write(buffer, 0, numRead); } source.Close(); destination.Close(); } } }
package com.comit.broadcast;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import com.comit.api.ApiService;
import com.comit.app.AppHpler;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseStream;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.http.client.entity.FileUploadEntity;
/**
* @ClassName: UploadService
* @Description:上传服务
* @author: RockeyCai
* @date: 2015-11-05 上午14:14:59
*
*/
public class UploadService extends Service {
// 上传标记
public static final String UPLOAD_SERVICE_DO_UPLOAD_FLAG = "UPLOAD_SERVICE_DO_UPLOAD_FLAG";
// 开始上传标记
public static final boolean UPLOAD_SERVICE_DO_UPLOAD_TRUE = true;
// 停止上传标记
public static final boolean UPLOAD_SERVICE_DO_UPLOAD_FALSE = false;
private String tag = UploadService.class.getCanonicalName();
private Timer timer;
private TimerTask mTimerTask;
private boolean isRun = false;
// 上传单线程池
private ExecutorService pool;
@Override
public IBinder onBind(Intent intent) {
return null;
}
public void onCreate() {
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
boolean uploadFlag = intent.getBooleanExtra(UPLOAD_SERVICE_DO_UPLOAD_FLAG, false);
if (uploadFlag) {
uploadImageTimer();
} else {
stopUploadImage();
}
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
// 停止上传服务
stopUploadImage();
}
/**
* 启动上传时间任务
*/
private void uploadImageTimer() {
stopUploadImage();
isRun = true;
timer = new Timer();
mTimerTask = new TimerTask() {
@Override
public void run() {
if (isRun) {
onUploadImage();
}
}
};
// 延迟30秒,启动服务
timer.schedule(mTimerTask, 30 * 1000);
}
/**
* 开始上传服务
*/
private void onUploadImage() {
Log.i(tag, "时间任务执行中....");
if (pool == null) {
pool = Executors.newSingleThreadExecutor();
}
for (File tempFile : this.getFileList()) {
// 单例线程池,处理上传任务列表
pool.execute(new UploadTask(tempFile));
}
}
/**
* @ClassName: UploadTask
* @Description:上传图片任务
* @author: RockeyCai
* @date: 2015-11-6 下午3:52:18
*
*/
class UploadTask implements Runnable {
File file = null;
String url = null;
public UploadTask(File file) {
this.file = file;
this.url = ApiService.UPLOAD_IMG;
}
@Override
public void run() {
// TODO Auto-generated method stub
Log.i(tag, "上传文件:" + file.getName());
// 设置超时时间为180秒,防止上传超时
HttpUtils httpUtils = new HttpUtils(60 * 3 * 1000);
RequestParams params = new RequestParams();
FileUploadEntity FileUploadEntity = new FileUploadEntity(file, "application/json; charset=utf-8");
params.setBodyEntity(FileUploadEntity);
params.addHeader(ApiService.API_KEY_NAME, ApiService.API_KEY_VALUE);
params.addHeader("UM_ID", "1");
params.addHeader("U_ID", "2");
params.addHeader("NAME", file.getName());
try {
ResponseStream responseStream = httpUtils.sendSync(HttpRequest.HttpMethod.POST, url, params);
String result = responseStream.readString();
if (result.indexOf("true") > -1) {
Log.i(tag, "上传结果....:" + result);
//上传成功处理
updateFileState(0);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.i(tag, "上传失败....:" + e.getMessage());
}
}
}
/**
* 停止上传服务
*/
private void stopUploadImage() {
if (timer != null) {
if (mTimerTask != null) {
mTimerTask.cancel();
mTimerTask = null;
}
timer.cancel();
timer = null;
isRun = false;
}
if (pool != null) {
// 关闭线程池
pool.shutdown();
}
}
/**
* @Title: getFileList
* @Description: 获取上传的文件列表
* @param: @return
* @return: List<File>
*/
private List<File> getFileList() {
//TODO 模拟获取数据源
List<File> fileList = new ArrayList<File>();
String path = AppHpler.getPath() + "/youku/img";
Log.i(tag, path);
File file = new File(path);
if (file.exists()) {
if (pool == null) {
pool = Executors.newSingleThreadExecutor();
}
for (File tempFile : file.listFiles()) {
if (tempFile.isFile()) {
fileList.add(tempFile);
}
}
}
return fileList;
}
/**
* @Title: updateFileState
* @Description: 修改上传文件列表
* @param: @param id
* @return: void
*/
private void updateFileState(long id){
//TODO 修改上传文件列表
}
}