WCF发布一个byte []来服务?

时间:2017-04-08 17:09:48

标签: c# web-services wcf http-post

我试图将byte []或FromBase64String字符串发布到我的webservice。我一直收到404错误。我已将["内容类型"]更改为" text / plain"并仍然得到错误。但是当我注释掉byteArray时,一切都很好。有没有人有建议?

客户端:

public class MainWindow extends JFrame {

    private static final int DEFAULT_WIDTH = 1400;
    private static final int DEFAULT_HEIGHT = 800;

    private JPanel mainPanel;

    public MainWindow() {
        setup();
    }

    private void setup() {
        this.setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
        this.setLocationRelativeTo(null);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setVisible(true);
        this.setExtendedState(getExtendedState() | JFrame.MAXIMIZED_BOTH);

        this.mainPanel = new JPanel(new BorderLayout());
        mainPanel.setBackground(Color.BLUE);

        this.add(mainPanel);
        setupObjectInsertPanel();
    }

    private void setupObjectInsertPanel() {

        JLabel label = new JLabel("TileSets");
        mainPanel.add(label, BorderLayout.NORTH);

        try{
            BufferedImage tilesetImage = ImageIO.read(new File(...)); // path ommitted
            JLabel tilesetIcon = new JLabel(new ImageIcon(tilesetImage));
            mainPanel.add(tilesetIcon, BorderLayout.SOUTH);
            System.out.println("Loaded tileset into panel");
        } catch (IOException e) {
            System.out.println("Could not open tileset");
            e.printStackTrace();
        }

    }
}

服务:

      Object _object = new Object
        {
            Param1String = "data",
            Param2String= "data",           
            Param3String = "data",
            ByteArray = ReadAllBytes(@"C:\Folder\test.pdf")
        };

        try
        {
            WebClient Proxy = new WebClient();                
            Proxy.Headers["Content-type"] = "application/json";                
            MemoryStream stream = new MemoryStream();
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Object));
            serializer.WriteObject(stream, _object);
            byte[] data = Proxy.UploadData("http://localhost:4589/TestService.svc/FileUpload", "POST", stream.ToArray());

            stream = new MemoryStream(data);
            serializer = new DataContractJsonSerializer(typeof(Object));
            var result = serializer.ReadObject(stream) as Object;
            Console.WriteLine(result.Param1String);
            Console.ReadKey(true);
        }
        catch (Exception ex)
        {

        }

1 个答案:

答案 0 :(得分:0)

在序列化对象之前,您需要对filecontent进行base64编码。并将其转换回另一侧的byte []

Object _object = new Object
    {
        Param1String = "data",
        Param2String= "data",           
        Param3String = "data",
        Base64ByteArray =  Convert.ToBase64String(ReadAllBytes(@"C:\Folder\test.pdf"))
    };