android上传图片、视频、文件,服务端使用wcf接收

最近一直在搞android上传图片、视频、文件,服务端使用wcf接收,本文对调试中的遇到的问题进行记录。

       首先android上传一些小图片是比较容易的一天下来差不多就能调试出来,但是上传一些大的文件时就出现各种问题,包括wcf默认支持64k的文件,后来大图片可以上传了,但是传视频又有问题,上传的视频打不开,经过努力google最后问题终于解决了。作者kwstu QQ806693619

以下是调试代码:原文链接:http://www.kwstu.com/ArticleView/kwstu_2013327194830639

一、Android:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package com.kwstu.palmjn;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
 
public class UpladeActivity extends Activity {
   private Button update_btn;
   private ImageView img_img;
   /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.uploadactivity);
      findAll();
      bind();
   }
   public void findAll() {
      update_btn = (Button) this.findViewById(R.id.update_btn);
      img_img = (ImageView) this.findViewById(R.id.img_img);
   }
   public void bind() {
      update_btn.setOnClickListener(mylistener);
   }
   private View.OnClickListener mylistener = new OnClickListener() {
      public void onClick(View v) {
         // TODO Auto-generated method stub
         switch (v.getId()) {
         case R.id.update_btn:
            Thread th1 = new Thread(new mythread());
            th1.start();
            break;
         default:
            break;
         }
      }
   };
 
   Handler hd = new Handler() {
      @Override
      public void handleMessage(Message msg) {
         // TODO Auto-generated method stub
         // super.handleMessage(msg);
         if (msg.what == 123) {
            String jason = msg.obj.toString();
            String filepath = Environment.getExternalStorageDirectory()
                   + File.separator + jason;
            Bitmap bitmap1 = BitmapFactory.decodeFile(filepath);
            img_img.setImageBitmap(bitmap1);
         }
      }
   };
 
   class mythread implements Runnable {
      public void run() {
         // TODO Auto-generated method stub
         HttpClient hc = new DefaultHttpClient();
         HttpPost hp = new HttpPost(wcf地址);
         HttpResponse hr;
         InputStreamEntity reqEntity;
         String path = 上传文件路径;
         File f = new File(path);
         if (f.exists()) {
            System.out.println("successful");
            try {
                reqEntity = new InputStreamEntity(new FileInputStream(path), -1);
                reqEntity.setContentType("binary/octet-stream");
                reqEntity.setChunked(true); // Send in multiple parts if needed
                hp.setEntity(reqEntity);
                System.out.println("4");
                HttpResponse response = hc.execute(hp);
                System.out.println("5");
            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                System.out.println(e.getMessage());
                //e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                //e.printStackTrace();
                System.out.println(e.getMessage());
            }
         }
      }
   }
}

Wcf代码:

接口

1
2
3
[OperationContract]
[WebInvoke(BodyStyle = WebMessageBodyStyle.WrappedRequest, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
string update_pictrue(Stream getStream);

实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
public string update_pictrue(Stream getStream)
        {
            Console.WriteLine("setData service has bean started!");
            string uploadFolder = @"C:\kkk\";
            string savaPath = "sss";
            //string dateString = DateTime.Now.ToShortDateString() + @"\";
            string fileName ="ddd.mp4";
            //Stream sourceStream = request.FileData;
            FileStream targetStream = null;
            if (!getStream.CanRead)
            {
                throw new Exception("数据流不可读!");
            }
            if (savaPath == null) savaPath = @"Photo\";
            if (!savaPath.EndsWith("\\")) savaPath += "\\";
            uploadFolder = uploadFolder + savaPath; //+ dateString;
            if (!Directory.Exists(uploadFolder))
            {
                Directory.CreateDirectory(uploadFolder);
            }
            string filePath = Path.Combine(uploadFolder, fileName);
            using (targetStream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None))
            {
                //read from the input stream in 4K chunks
                //and save to output stream
                const int bufferLen = 4096;
                byte[] buffer = new byte[bufferLen];
                int count = 0;
                while ((count = getStream.Read(buffer, 0, bufferLen)) > 0)
                {
                    targetStream.Write(buffer, 0, count);
                }
                targetStream.Close();
                getStream.Close();
            }
            return "";
        }

配置很重要必须支持大文件上传

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<?xml version="1.0"?>
<configuration>
    <system.serviceModel>
      <behaviors>
        <serviceBehaviors>
          <behavior name="Host.ServiceBehavior">
            <serviceMetadata httpGetEnabled="true"/>
            <serviceDebug includeExceptionDetailInFaults="false"/>
            <dataContractSerializer maxItemsInObjectGraph="2147483647"/>
          </behavior>
        </serviceBehaviors>
        <endpointBehaviors>
          <behavior name="json">
            <enableWebScript />
          </behavior>
        </endpointBehaviors>
      </behaviors>
      <services>
        <service name="Host.Service" behaviorConfiguration="Host.ServiceBehavior">
          <endpoint  binding="webHttpBinding" contract="Host.IService" behaviorConfiguration="json" bindingConfiguration="LargeBuffer">
          <identity>
            <dns value="localhost"/>
          </identity>
          </endpoint>
          <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
          <host>
            <baseAddresses>
              <add baseAddress="http://localhost:8732/Mush/Host/Service/"/>
            </baseAddresses>
          </host>
        </service>
      </services>
     
 
      <bindings>
        <webHttpBinding>
          <binding name="LargeBuffer"
          maxBufferSize="2147483647" maxReceivedMessageSize="2147483647">
            <readerQuotas
            maxStringContentLength="2147483647" maxArrayLength="2147483647"/>
            <security mode="None"></security>
          </binding>
        </webHttpBinding>
      </bindings>
    </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup></configuration>
posted @ 2015-06-10 12:00  冰峰剑心  阅读(1797)  评论(0编辑  收藏  举报