简体   繁体   English

Python至.net Web服务映像已创建但已损坏

[英]Python to .net web service Image created but corrupted

I am sending an image and other parameters from python to a web service (.net) endpoint. 我正在将图像和其他参数从python发送到Web服务(.net)端点。 While I convert it to byte and then write to disk, the image created can not be displayed... error is 'the image can not displayed because it contains error'. 当我将其转换为字节然后写入磁盘时,创建的图像无法显示...错误是“由于包含错误,无法显示该图像”。 Here is my code in python... 这是我在python中的代码...

def upload_form():
    header = {'Content-Type':'application/json'}
    params = {'imagefile':bx64, 'sacid':'3', 'astid':'188', 'docName':'abc4', 'docExtn':'png'}
    url='http://localhost:47176/snapshot.svc/DoUpload'
    selector =''

    try:
        _data = dumps(params)           
        req = request.Request(url)
        connection = http.client.HTTPConnection(req.host)
        connection.request ('POST', req.selector, _data, header)
        response = connection.getresponse()
        print('response = %s', response.read())
    except Exception as e:
        print('Error...', e)

bx64 = get_b64string('some png file name')

def get_b64string(file):
    ENCODING = 'utf-8'

    with open(file, 'rb') as open_file:
        return b64encode(open_file.read()).decode(ENCODING)

While at server side, endpoint code is... 在服务器端,端点代码是...

    public string DoUpload(string imagefile, string sacid, string astid, string docName, string docExtn)
    {
        string m_fileName = string.Format("{0}.{1}", docName, docExtn.Replace(".", ""));
        string m_host = string.Format("{0}/{1}", FTPUrl, sacid.ToString());

        try
        {
            byte[] imgbinaryarray = Encoding.UTF8.GetBytes(imagefile);
            if (UploadToFtp(imgbinaryarray, FTPUrl, Convert.ToInt32(sacid), Convert.ToInt32(astid), m_fileName)) return "OK";
        }
        catch (Exception ex)
        {
            //Log and return error                
            return ex.Message;
        }
        return "File could not be processed, contact application support!";
    }

Edited: I have modified the code to use 'requests' library in python and also the end point accordingly. 编辑:我已经修改了代码以在python中使用“ requests”库,并相应地在了终点。

End Point: 终点:

    [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json)]
    public string DoFileUpload(Stream fileContent)
    {
        string docName = "abc-"+DateTime.Now.Ticks.ToString();
        string m_fileName = string.Format("{0}.jpg",docName);

        string filePath = string.Format("C:\\Temp\\Upload\\{0}", m_fileName);
        try
        {
            using (var fs = new FileStream(filePath, FileMode.Create, FileAccess.Write))
            {
                fileContent.CopyTo(fs);
            }
            return "OK";        
        }
        catch (Exception ex)
        {   
            return ex.Message;
        }
    }

Python Code: Python代码:

        def upload_form3(fileToUpload):
        try:
            url = 'http://localhost:47176/snapshot.svc/DoFileUpload'
            files = {'fileContent':open(fileToUpload,'rb')}             
            r = requests.post(url, files=files)
            print(r.text)
        except Exception as e:
            print('upload_form3. Error...', e)

Still the file created is showing same error ie can not open file contains error. 创建的文件仍然显示相同的错误,即无法打开包含错误的文件。

Used like you are doing, requests will post a MIME multipart-encoded data, which your .Net side does not expect (it looks like it expects a simple stream, but I don't know .net enough to be sure). 就像您正在使用的那样,请求将发布MIME多部分编码的数据,您的.Net端不希望使用此数据(它看起来像希望使用简单的流,但我不太了解.net可以肯定)。

Try with this python client code, it sends the file content as a simple stream: 尝试使用以下python客户端代码,它将文件内容作为简单流发送:

def upload_form3(fileToUpload):
    try:
        url = 'http://localhost:47176/snapshot.svc/DoFileUpload'  
        with open(fileToUpload,'rb') as finput:
            r = requests.post(url, data=finput)
        print(r.text)
    except Exception as e:
        print('upload_form3. Error...', e)

Thank you all, I am sorry that I came back late. 谢谢大家,对不起我回来晚了。 The solution which I used is to read the stream in a memory stream, strip the initial bytes containing meta data / header information. 我使用的解决方案是读取内存流中的流,剥离包含元数据/标头信息的初始字节。 Then write it to file and the image is correctly created. 然后将其写入文件,即可正确创建映像。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM