Android的上传图片到WCF服务"参数是无效的和QUOT。上传图片、参数、Android、QUOT

2023-09-05 10:09:36 作者:一饮山河尽

从库中选择一个图像,我可以上传一个流,但得到的错误参数是无效的。当试图转换为图像WCF。

Selecting an image from gallery, I am able to upload a stream, but get the error "Parameter is not valid." when trying to convert to image in WCF.

Android的code创建连接到REST服务和上传图像字节]:

Android code creates connection to REST service and uploads image as Byte[]:

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  super.onActivityResult(requestCode, resultCode, data);

  if (resultCode == RESULT_OK){
    Uri targetUri = data.getData();

    Bitmap bitmap;
    try {
      bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(targetUri));
      ByteArrayOutputStream out = new ByteArrayOutputStream();

      bitmap.compress(Bitmap.CompressFormat.JPEG, 6, out);

      DefaultHttpClient httpClient = new DefaultHttpClient();

      byte[] sendData = out.toByteArray();

      HttpPost postRequest = new HttpPost("https://m.xsw88.com/allimgs/daicuo/20230905/2101.png.jpg");
      MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
      reqEntity.addPart("image", bab);
      postRequest.setEntity(reqEntity);
      httpClient.execute(postRequest);

WCF C#code接收数据流并尝试转换为图像,但收到的错误:

WCF C# code receives stream and tries to convert to an image, but receives error:

    public void UploadPicture(Stream imageData)
    {
        try
        {
            byte[] image = StreamToBytes(imageData);

            ImageConverter imageConverter = new ImageConverter();
            Image img = imageConverter.ConvertFrom(image) as Image; <-- Exception happens here

            SaveImage(img);
        }
        catch (Exception ex)
        {
            Log(ex.ToString());
        }
    }

    private byte[] StreamToBytes(Stream stream)
    {
        byte[] output = new byte[0];
        byte[] stream_array = new byte[0];
        byte[] buffer = new byte[1024];
        int read;

        while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
        {
            stream_array = new byte[output.Length + read];
            output.CopyTo(stream_array, 0);
            Array.Copy(buffer, 0, stream_array, output.Length, read);
            output = stream_array;
        }

        return output;
    }

我是什么做错了吗?

What am I doing wrong?

推荐答案

我想先解释一下为什么首先发生的问题,然后给你的解决方案: 试试这个实验上的code。而不是你使用了下列code,用code是低于替代它:

I would like to first explain why the issue occurred first and then give you the solution: Try this experiment on your code. Instead of the following code which you have used, replace it with the code which is below that:

       public void UploadPicture(Stream imageData)
       {
           try
           {
               byte[] image = StreamToBytes(imageData);
               ImageConverter imageConverter = new ImageConverter();
               Image img = imageConverter.ConvertFrom(image) as Image;
               SaveImage(img);
           }
           catch (Exception ex)
           {
               Log(ex.ToString());
           }
       }

替换,

    public void UploadPicture (Stream imageData)
    {
        try
        {
            byte[] buffer = new byte[10000];
            imagedata.Read(buffer, 0, 10000);
            FileStream f = new FileStream("D:\\FileUpload\\SubjectFront.JPG", FileMode.OpenOrCreate);
            f.Write(buffer, 0, buffer.Length);
            f.Close();
            imagedata.Close();
        }
        catch (Exception ex)
        {
        } 
    }

这code没有任何异常(我相信)执行,你会发现在保存路径的图像文件。请注意,这是在D所创建的文件:\文件上传。该文件的大小是比你的android code发送的文件尺寸大得多(即,如果您还没有COM pressed它)。尝试使用任何图像编辑器中打开该文件,它会打开一个已损坏的文件(你将无法看到的图像)。

This code executes without any exception (I believe) and you would find the image file in the "saved" path. Notice the file which is created in your D:\FileUpload. The size of the file is much larger than the size of the file sent by your android code(i.e. if you have not compressed it). Try opening this file with any image editor and it would open as a corrupted file (you would not be able to see the image).

现在用记事本打开该文件。人们可以看到,随着乱码的二进制数据,也有一些可用的文本。示例: - 的 内容处置:表格数据; ......等等等等的。本文是罪魁祸首为贵的参数无效异常。而在Java使用多部分,它增加了该文本并将其沿其转化为字节流中的图像数据发送。我不知道为什么会做到这一点。 现在,删除任何人类可读的文本,并保存文件。打开任何图像编辑器和中提琴的文件中,有你的形象。

Now open the file with notepad. One could see that along with the garbled binary data, there is also some text available. Example: -- Content-Disposition: form-data;….. blah blah. This text is the culprit for your "Parameter is not valid" exception. While using Multipart in java, it adds this text and send it along the image data which is converted to byte stream. I’m not sure why it does that. Now, remove any human readable text and save the file. Open the file in any image editor and viola, there is your image.

现在,解决的办法是写一个code删除从收到的WCF方法的流此文本。我发现了一个很漂亮的解析器写(感谢安东尼),能有效地做这项工作。你可以在这里找到它( HTTP://multipartparser.$c$cplex.com/ )。就在这个cs文件添加到您的项目,并完成类似下面。

Now, the solution lies in to write a code to remove this text from the stream which is received by the WCF method. I found a very beautiful parser written(Thanks to Anthony) which does the job efficiently. You can find it here (http://multipartparser.codeplex.com/). Just add this .cs file to your project and do something like below.

    public string UploadPicture (Stream imagedata)
    {
        MultipartParser parser = new MultipartParser(imagedata);

        if (parser.Success)
        {
            string fileName = parser.Filename;
            string contentType = parser.ContentType;
            byte[] fileContent = parser.FileContents;
            System.Drawing.Image image = byteArrayToImage(fileContent);
            image.Save("D:\\FileUpload\\" + fileName);
            return "Success !!!";
         }
         else
         {
            return "Exception!!!";
         }
   }

byteArrayToImage的实施情况如下:

The implementation of byteArrayToImage is as follows:

public System.Drawing.Image byteArrayToImage(byte[] byteArrayIn)
{
    MemoryStream ms = new MemoryStream(byteArrayIn);
    System.Drawing.Image returnImage = System.Drawing.Image.FromStream(ms);
    return returnImage;
}

希望它帮助...

Hope it has helped…