Python到.net web服务映像已创建但已损坏

2024-10-02 08:16:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我将图像和其他参数从python发送到web服务(.net)端点。当我把它转换成字节然后写入磁盘时,创建的图像无法显示。。。错误是“图像无法显示,因为它包含错误”。这是我用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)

在服务器端,端点代码是

    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!";
    }

编辑时间: 我修改了代码以使用python中的'requests'库,并相应地修改了端点

终点:

    [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代码:

        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)

创建的文件仍然显示相同的错误,即无法打开包含错误的文件


Tags: 代码formaturlstringreturn错误exceptionopen
2条回答

像您正在做的那样使用,请求将发布MIME多部分编码的数据,这是您的.Net端不希望看到的(看起来它需要一个简单的流,但我对.Net的了解还不够确定)

尝试使用此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)

谢谢大家,很抱歉我回来晚了。我使用的解决方案是读取内存流中的流,去掉包含元数据/头信息的初始字节。然后将其写入文件,图像就被正确创建

相关问题 更多 >

    热门问题