Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/313.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 将多部分文件从android上载到WCF_Java_C#_Android_Wcf_File Upload - Fatal编程技术网

Java 将多部分文件从android上载到WCF

Java 将多部分文件从android上载到WCF,java,c#,android,wcf,file-upload,Java,C#,Android,Wcf,File Upload,我正在尝试将.JPG文件从android上传到WCF webservice 要从Android上传文件,我尝试了两种方法: 1- b-将文件对象加载到请求参数: 所有这些,成功发送到服务器,解析前收到的文件如下所示: --b1b13fd2-4212-45bb-bb5c-fd4dc074fd1b Content-Disposition: form-data; name="image"; filename="71d9d7fc-cfa8-40b6-b7aa-5c287cf31c72.jpg" Cont

我正在尝试将.JPG文件从android上传到WCF webservice

要从Android上传文件,我尝试了两种方法:

1-

b-将文件对象加载到请求参数:

所有这些,成功发送到服务器,解析前收到的文件如下所示:

--b1b13fd2-4212-45bb-bb5c-fd4dc074fd1b
Content-Disposition: form-data; name="image"; filename="71d9d7fc-cfa8-40b6-b7aa-5c287cf31c72.jpg"
Content-Type: image/jpeg
Content-Length: 2906
Content-Transfer-Encoding: binary

���� JFIF      �� C .................very long string of this stuff
Þq�Ã�9�A?� �0pi1�zq�<�#��:��PV���]|�e�K�mv �ǜ.1�q���&��8��u�m�?�ӵ/���0=8�x�:t�8��>�ׁ���1�POM�k����eea1��ǧq�}8�6��q� � �� .;p1K�g�Onz�Q�oås�a�׌p1�?>3@���z��0=��m$�H ǧ��Ӄ�v?��x��<q��.8܃��� ��2}1�� c���ϧ q�oA�Rt>��t�=�?����2y�q�큊A����:��q�@���_�~�Q�w��Pu��Ƿ�q�#q��{cۦ���}0:b�|�=@��9�BEV���?O��װ�g���׎z<N� ��� v�=�?������=�<}x�#'�d�8��׌e����,�\�4wVV���f�pB���㢁�L{��%$�v裶G8x��b�?���� �]�=:�ӕ����
--b1b13fd2-4212-45bb-bb5c-fd4dc074fd1b--
服务中心:

[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "/UploadFile/{fileName}"
  , ResponseFormat = WebMessageFormat.Json)]
string UploadFile(string fileName ,Stream image);
public string UploadFile(string fileName, Stream image)
{
  string dirPath = System.Web.Hosting.HostingEnvironment.MapPath("~/Logs/");
  //string path = dirPath+"log.txt";

  // Read the stream into a byte array
  byte[] data = MultipartParser.ToByteArray(image);

  // Copy to a string
  string content = Encoding.UTF8.GetString(data);

  File.WriteAllText(dirPath + fileName + ".txt", content); // for checking the result file

  MultipartParser parser = new MultipartParser(content);

  if (parser != null )
  {
    if (parser.Success)
    {

      if (parser.FileContents == null)
        return "fail: Null Content";

      byte[] bitmap = parser.FileContents;

      File.WriteAllBytes(dirPath + fileName +"contents",bitmap);

      try
      {
        using (Image outImage = Image.FromStream(new MemoryStream(bitmap)))
        {
          outImage.Save(fileName, ImageFormat.Jpeg);
        }
        return "success";
      }
      catch (Exception e)
      { // I get this exception all the time
        return "Fail: e " + e.Message;
      }
    }
    return "fail not success";
  }

  return "fail";
}
我尝试了所有可能的解决方案,但仍然没有得到什么错误!!!是发送时的编码问题还是解析器问题

请问有什么问题!?我为此挣扎了三天


谢谢大家:)

在发送之前,您可以尝试将jpeg编码为base64。据我所知,这是一个适当的解决办法。在服务器上解码应该没有问题。(Sry,我想写一篇评论,但我不允许写)

有两个问题:

  • 解析器
  • 将字节解码为字符串不是个好主意
  • 我将解析器修改为这一个,它将处理其余部分:

    public class MultipartParser
    
    
    {
        public MultipartParser(Stream stream)
    {
      this.Parse(stream);
    }
    
    private void Parse(Stream stream)
    {
      this.Success = false;
      if(!stream.CanRead)
        return;
    
      // Read the stream into a byte array
      byte[] data = MultipartParser.ToByteArray(stream);
      if (data.Length < 1)
        return;
    
      // finding the delimiter (the string in the beginning and end of the file
      int delimeterIndex = MultipartParser.SimpleBoyerMooreSearch(data, Encoding.UTF8.GetBytes("\r\n")); // here we got delimeter index
      if (delimeterIndex == -1) return;
      byte[] delimeterBytes = new byte[delimeterIndex];
      Array.Copy(data, delimeterBytes, delimeterIndex);
    
      // removing the very first couple of lines, till we get the beginning of the JPG file
      byte[] newLineBytes = Encoding.UTF8.GetBytes("\r\n\r\n");
      int startIndex = 0;
    
      startIndex = MultipartParser.SimpleBoyerMooreSearch(data, newLineBytes);
      if (startIndex == -1)
        return;
    
      int startIndexWith2Lines = startIndex + 4; // 4 is the bytes of "\r\n\r\n"
      int newLength = data.Length - startIndexWith2Lines;
      byte[] newByteArray = new byte[newLength];
    
      Array.Copy(data, startIndex + 4, newByteArray, 0, newLength - 1);
    
      // check for the end of the stream, is ther same delimeter
      int isThereDelimeterInTheEnd = MultipartParser.SimpleBoyerMooreSearch(newByteArray, delimeterBytes);
      if (isThereDelimeterInTheEnd == -1) return; // the file corrupted so
    
      int endIndex = isThereDelimeterInTheEnd - delimeterBytes.Length;
    
      byte[] lastArray = new byte[endIndex];
    
      Array.Copy(newByteArray, 0, lastArray, 0, endIndex);
    
      this.FileContents = lastArray;
      this.Success = true;
    }
    static byte[] GetBytes(string str)
    {
      byte[] bytes = new byte[str.Length * sizeof(char)];
      System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
      return bytes;
    }
    
    static string GetString(byte[] bytes)
    {
      char[] chars = new char[bytes.Length / sizeof(char)];
      System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
      return new string(chars);
    }
    
    
    public static int SimpleBoyerMooreSearch(byte[] haystack, byte[] needle)
    {
      int[] lookup = new int[256];
      for (int i = 0; i < lookup.Length; i++) { lookup[i] = needle.Length; }
    
      for (int i = 0; i < needle.Length; i++)
      {
        lookup[needle[i]] = needle.Length - i - 1;
      }
    
      int index = needle.Length - 1;
      byte lastByte = needle.Last();
      while (index < haystack.Length)
      {
        var checkByte = haystack[index];
        if (haystack[index] == lastByte)
        {
          bool found = true;
          for (int j = needle.Length - 2; j >= 0; j--)
          {
            if (haystack[index - needle.Length + j + 1] != needle[j])
            {
              found = false;
              break;
            }
          }
    
          if (found)
            return index - needle.Length + 1;
          else
            index++;
        }
        else
        {
          index += lookup[checkByte];
        }
      }
      return -1;
    }
    
    private int IndexOf(byte[] searchWithin, byte[] serachFor, int startIndex)
    {
      int index = 0;
      int startPos = Array.IndexOf(searchWithin, serachFor[0], startIndex);
    
      if (startPos != -1)
      {
        while ((startPos + index) < searchWithin.Length)
        {
          if (searchWithin[startPos + index] == serachFor[index])
          {
            index++;
            if (index == serachFor.Length)
            {
              return startPos;
            }
          }
          else
          {
            startPos = Array.IndexOf<byte>(searchWithin, serachFor[0], startPos + index);
            if (startPos == -1)
            {
              return -1;
            }
            index = 0;
          }
        }
      }
    
      return -1;
    }
    
    public static byte[] ToByteArray(Stream stream)
    {
      byte[] buffer = new byte[32768];
      using (MemoryStream ms = new MemoryStream())
      {
        while (true)
        {
          int read = stream.Read(buffer, 0, buffer.Length);
          if (read <= 0)
            return ms.ToArray();
          ms.Write(buffer, 0, read);
        }
      }
    }
    
    public bool Success
    {
      get;
      private set;
    }
    
    public byte[] FileContents
    {
      get;
      private set;
    }
    
    
    }
    
    公共类多部分解析器
    {
    公共多部分解析器(流)
    {
    解析(流);
    }
    私有void解析(流)
    {
    成功=错误;
    如果(!stream.CanRead)
    返回;
    //将流读入字节数组
    byte[]data=MultipartParser.ToByteArray(流);
    如果(数据长度<1)
    返回;
    //查找分隔符(文件开头和结尾的字符串
    int delimeterIndex=MultipartParser.simpleboyermoresearch(data,Encoding.UTF8.GetBytes(“\r\n”);//这里是delimeter索引
    如果(delimeterIndex==-1)返回;
    字节[]delimeterBytes=新字节[delimeterIndex];
    复制(数据,delimeterBytes,delimeterIndex);
    //删除最开始的几行,直到我们得到JPG文件的开头
    byte[]newLineBytes=Encoding.UTF8.GetBytes(“\r\n\r\n”);
    int startIndex=0;
    startIndex=MultipartParser.SimpleBoyerMooreSearch(数据,newLineBytes);
    如果(startIndex==-1)
    返回;
    int startIndexWith2Lines=startIndex+4;//4是“\r\n\r\n”的字节
    int newLength=data.Length-startindexwith2line;
    字节[]新字节数组=新字节[newLength];
    复制(数据,startIndex+4,newByteArray,0,newLength-1);
    //检查流的末端,是否有相同的delimeter
    int isThereDelimeterInTheEnd=MultipartParser.SimpleByerMooreSearch(新字节数组,delimeterBytes);
    if(isThereDelimeterInTheEnd==-1)返回;//文件已损坏,因此
    int endIndex=IstheratedElimeterinTheend-delimeterBytes.Length;
    字节[]lastArray=新字节[endIndex];
    Copy(newByteArray,0,lastArray,0,endIndex);
    this.FileContents=lastArray;
    这就是成功;
    }
    静态字节[]获取字节(字符串str)
    {
    byte[]bytes=新字节[str.Length*sizeof(char)];
    System.Buffer.BlockCopy(str.ToCharArray(),0,bytes,0,bytes.Length);
    返回字节;
    }
    静态字符串GetString(字节[]字节)
    {
    char[]chars=新字符[bytes.Length/sizeof(char)];
    System.Buffer.BlockCopy(字节,0,字符,0,字节.长度);
    返回新字符串(字符);
    }
    公共静态int-SimpleBoyerMooreSearch(字节[]干草堆,字节[]针)
    {
    int[]查找=新int[256];
    对于(inti=0;i=0;j--)
    {
    如果(草堆[索引-针.长度+j+1]!=针[j])
    {
    发现=错误;
    打破
    }
    }
    如果(找到)
    返回索引-针。长度+1;
    其他的
    索引++;
    }
    其他的
    {
    索引+=查找[检查字节];
    }
    }
    返回-1;
    }
    private int IndexOf(字节[]searchWithin,字节[]serachFor,int startIndex)
    {
    int指数=0;
    int startPos=Array.IndexOf(searchWithin,serachFor[0],startIndex);
    如果(startPos!=-1)
    {
    while((startPos+索引)如果(阅读“解析器正在取出字节,并解析收到的多部分文件”。。我不理解WCF代码。但是,如果取出了文件的字节,那么您就准备好了。为什么还要解析其他内容呢?只需将字节保存到文件中。因此,您应该将“数据”写入文件。不要将“数据”转换为utf字符串。不要使用“内容”。保存“数据”。“流图像”)“。非常混乱,因为这不是一个图像。但是图像字节被标题文本包围。为了更好的可读性,最好改为“Stream Stream”。和“data”不是我最初假设的图像字节。“并解析接收到的多部分文件。”。您的图像文件不是多部分的。而且您不仅接收到一个文件。混乱。更好的spea。”k关于收到的多部分数据。该数据的一部分是您的文件。'MultipartParser=new MultipartParser(content);'。能否将其更改为MultipartParser=new MultipartParser(data)?@greenapps你说得对,我要做更改,我几乎解决了问题,基本上编码中的问题。这段代码对flutter仍然不起作用。你能帮我解决这个问题吗?
    
      public class MultipartParser
       {
    public MultipartParser(string contents)
    {
      this.Parse(contents);
    }
    
    private void Parse(string contents)
    {
      Encoding encoding = Encoding.UTF8;
      this.Success = false;
    
      // Read the stream into a byte array
      byte[] data = encoding.GetBytes(contents);
    
      // Copy to a string for header parsing
      string content = contents;
    
      // The first line should contain the delimiter
      int delimiterEndIndex = content.IndexOf("\r\n");
    
      if (delimiterEndIndex > -1)
      {
        string delimiter = content.Substring(0, content.IndexOf("\r\n"));
    
        // Look for Content-Type
        Regex re = new Regex(@"(?<=Content\-Type:)(.*?)(?=\r\n)");
        Match contentTypeMatch = re.Match(content);
    
        // Look for filename
        re = new Regex(@"(?<=filename\=\"")(.*?)(?=\"")");
        Match filenameMatch = re.Match(content);
    
        #region added
        re = new Regex(@"(?<=Content\-Transfer\-Encoding:)(.*?)(?=\r\n\r\n)");
        Match contentTransferEncodingMatch = re.Match(content);
        #endregion
    
        // Did we find the required values?
        if (contentTypeMatch.Success && filenameMatch.Success && contentTransferEncodingMatch.Success)
        {
          // Set properties
          this.ContentType = contentTypeMatch.Value.Trim();
          this.Filename = filenameMatch.Value.Trim();
          this.ContentEncoding = contentTransferEncodingMatch.Value.Trim();
    
    
          // Get the start & end indexes of the file contents
          //int startIndex = contentTypeMatch.Index + contentTypeMatch.Length + "\r\n\r\n".Length;
          int startIndex = contentTransferEncodingMatch.Index + contentTransferEncodingMatch.Length + "\r\n\r\n".Length;
    
          byte[] delimiterBytes = encoding.GetBytes("\r\n" + delimiter);
          string finalDelimeterStr = "\r\n"+delimiter + "--";
          byte[] endDilimeterBytes = encoding.GetBytes(finalDelimeterStr);
          //byte[] fileBytes = Array.Copy()
          //int endIndex = IndexOf(data, endDilimeterBytes, startIndex);
          int endIndex = SimpleBoyerMooreSearch(data, endDilimeterBytes);
    
          int contentLength = endIndex - startIndex;
    
          // Extract the file contents from the byte array
          byte[] fileData = new byte[contentLength];
    
          Buffer.BlockCopy(data, startIndex, fileData, 0, contentLength);
    
          this.FileContents = fileData;
          this.Success = true;
        }
      }
    }
    
    public int SimpleBoyerMooreSearch(byte[] haystack, byte[] needle)
    {
      int[] lookup = new int[256];
      for (int i = 0; i < lookup.Length; i++) { lookup[i] = needle.Length; }
    
      for (int i = 0; i < needle.Length; i++)
      {
        lookup[needle[i]] = needle.Length - i - 1;
      }
    
      int index = needle.Length - 1;
      byte lastByte = needle.Last();
      while (index < haystack.Length)
      {
        var checkByte = haystack[index];
        if (haystack[index] == lastByte)
        {
          bool found = true;
          for (int j = needle.Length - 2; j >= 0; j--)
          {
            if (haystack[index - needle.Length + j + 1] != needle[j])
            {
              found = false;
              break;
            }
          }
    
          if (found)
            return index - needle.Length + 1;
          else
            index++;
        }
        else
        {
          index += lookup[checkByte];
        }
      }
      return -1;
    }
    
    public static byte[] ToByteArray(Stream stream)
    {
      byte[] buffer = new byte[32768];
      using (MemoryStream ms = new MemoryStream())
      {
        while (true)
        {
          int read = stream.Read(buffer, 0, buffer.Length);
          if (read <= 0)
            return ms.ToArray();
          ms.Write(buffer, 0, read);
        }
      }
    }
    
    public bool Success
    {
      get;
      private set;
    }
    
    public string ContentType
    {
      get;
      private set;
    }
    public string ContentEncoding
    {
      get;
      private set;
    }
    
    
    public string Filename
    {
      get;
      private set;
    }
    
    public byte[] FileContents
    {
      get;
      private set;
    }
    
    [OperationContract]
    [WebInvoke(Method = "POST", UriTemplate = "/UploadFile/{fileName}"
      , ResponseFormat = WebMessageFormat.Json)]
    string UploadFile(string fileName ,Stream image);
    
    public string UploadFile(string fileName, Stream image)
    {
      string dirPath = System.Web.Hosting.HostingEnvironment.MapPath("~/Logs/");
      //string path = dirPath+"log.txt";
    
      // Read the stream into a byte array
      byte[] data = MultipartParser.ToByteArray(image);
    
      // Copy to a string
      string content = Encoding.UTF8.GetString(data);
    
      File.WriteAllText(dirPath + fileName + ".txt", content); // for checking the result file
    
      MultipartParser parser = new MultipartParser(content);
    
      if (parser != null )
      {
        if (parser.Success)
        {
    
          if (parser.FileContents == null)
            return "fail: Null Content";
    
          byte[] bitmap = parser.FileContents;
    
          File.WriteAllBytes(dirPath + fileName +"contents",bitmap);
    
          try
          {
            using (Image outImage = Image.FromStream(new MemoryStream(bitmap)))
            {
              outImage.Save(fileName, ImageFormat.Jpeg);
            }
            return "success";
          }
          catch (Exception e)
          { // I get this exception all the time
            return "Fail: e " + e.Message;
          }
        }
        return "fail not success";
      }
    
      return "fail";
    }
    
    public class MultipartParser
    
    
    {
        public MultipartParser(Stream stream)
    {
      this.Parse(stream);
    }
    
    private void Parse(Stream stream)
    {
      this.Success = false;
      if(!stream.CanRead)
        return;
    
      // Read the stream into a byte array
      byte[] data = MultipartParser.ToByteArray(stream);
      if (data.Length < 1)
        return;
    
      // finding the delimiter (the string in the beginning and end of the file
      int delimeterIndex = MultipartParser.SimpleBoyerMooreSearch(data, Encoding.UTF8.GetBytes("\r\n")); // here we got delimeter index
      if (delimeterIndex == -1) return;
      byte[] delimeterBytes = new byte[delimeterIndex];
      Array.Copy(data, delimeterBytes, delimeterIndex);
    
      // removing the very first couple of lines, till we get the beginning of the JPG file
      byte[] newLineBytes = Encoding.UTF8.GetBytes("\r\n\r\n");
      int startIndex = 0;
    
      startIndex = MultipartParser.SimpleBoyerMooreSearch(data, newLineBytes);
      if (startIndex == -1)
        return;
    
      int startIndexWith2Lines = startIndex + 4; // 4 is the bytes of "\r\n\r\n"
      int newLength = data.Length - startIndexWith2Lines;
      byte[] newByteArray = new byte[newLength];
    
      Array.Copy(data, startIndex + 4, newByteArray, 0, newLength - 1);
    
      // check for the end of the stream, is ther same delimeter
      int isThereDelimeterInTheEnd = MultipartParser.SimpleBoyerMooreSearch(newByteArray, delimeterBytes);
      if (isThereDelimeterInTheEnd == -1) return; // the file corrupted so
    
      int endIndex = isThereDelimeterInTheEnd - delimeterBytes.Length;
    
      byte[] lastArray = new byte[endIndex];
    
      Array.Copy(newByteArray, 0, lastArray, 0, endIndex);
    
      this.FileContents = lastArray;
      this.Success = true;
    }
    static byte[] GetBytes(string str)
    {
      byte[] bytes = new byte[str.Length * sizeof(char)];
      System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
      return bytes;
    }
    
    static string GetString(byte[] bytes)
    {
      char[] chars = new char[bytes.Length / sizeof(char)];
      System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
      return new string(chars);
    }
    
    
    public static int SimpleBoyerMooreSearch(byte[] haystack, byte[] needle)
    {
      int[] lookup = new int[256];
      for (int i = 0; i < lookup.Length; i++) { lookup[i] = needle.Length; }
    
      for (int i = 0; i < needle.Length; i++)
      {
        lookup[needle[i]] = needle.Length - i - 1;
      }
    
      int index = needle.Length - 1;
      byte lastByte = needle.Last();
      while (index < haystack.Length)
      {
        var checkByte = haystack[index];
        if (haystack[index] == lastByte)
        {
          bool found = true;
          for (int j = needle.Length - 2; j >= 0; j--)
          {
            if (haystack[index - needle.Length + j + 1] != needle[j])
            {
              found = false;
              break;
            }
          }
    
          if (found)
            return index - needle.Length + 1;
          else
            index++;
        }
        else
        {
          index += lookup[checkByte];
        }
      }
      return -1;
    }
    
    private int IndexOf(byte[] searchWithin, byte[] serachFor, int startIndex)
    {
      int index = 0;
      int startPos = Array.IndexOf(searchWithin, serachFor[0], startIndex);
    
      if (startPos != -1)
      {
        while ((startPos + index) < searchWithin.Length)
        {
          if (searchWithin[startPos + index] == serachFor[index])
          {
            index++;
            if (index == serachFor.Length)
            {
              return startPos;
            }
          }
          else
          {
            startPos = Array.IndexOf<byte>(searchWithin, serachFor[0], startPos + index);
            if (startPos == -1)
            {
              return -1;
            }
            index = 0;
          }
        }
      }
    
      return -1;
    }
    
    public static byte[] ToByteArray(Stream stream)
    {
      byte[] buffer = new byte[32768];
      using (MemoryStream ms = new MemoryStream())
      {
        while (true)
        {
          int read = stream.Read(buffer, 0, buffer.Length);
          if (read <= 0)
            return ms.ToArray();
          ms.Write(buffer, 0, read);
        }
      }
    }
    
    public bool Success
    {
      get;
      private set;
    }
    
    public byte[] FileContents
    {
      get;
      private set;
    }
    
    
    }
    
    --b1b13fd2-4212-45bb-bb5c-fd4dc074fd1b
    Content-Disposition: form-data; name="image"; filename="71d9d7fc-cfa8-40b6-b7aa-5c287cf31c72.jpg"
    Content-Type: image/jpeg
    Content-Length: 2906
    Content-Transfer-Encoding: binary
    
    ���� JFIF      �� C .................very long string of this stuff
    Þq�Ã�9�A?� �0pi1�zq�<�#��:��PV���]|�e�K�mv �ǜ.1�q���&��8��u�m�?�ӵ/��Ƿ�q�#q��{cۦ���}0:b�|�=@��9�BEV���?O��װ�g���׎z<N� ��� v�=�?������=�<}x�#'�d�8��׌e����,�\�4wVV���f�pB���㢁�L{��%$�v裶G8x��b�?���� �]�=:�ӕ����
    --b1b13fd2-4212-45bb-bb5c-fd4dc074fd1b--