开发者

python not correctly uploading to php

I have a python script using mechanize to upload an image to a php script. The problem is that the image is 3,000kb yet only 52kb is showing on the server.

HERE IS THE PYTHON:

from mechanize import Browser
br = Browser()
br.open("http://w开发者_如何学编程ww.mattyc.com/up")
br.select_form(name="upper")
br.form.add_file(open("tester.jpg"), 'image/jpeg', "tester.jpg")
br.submit()

HERE IS THE WEB PAGE:

<?php
if (move_uploaded_file($_FILES['file']['tmp_name'], $_FILES["file"]["name"])) {
    $success_msg = "GOOD";
    echo $success_msg;
}else{
echo "ERROR";
}


?>
<html>
<head>
<title>UP</title>
</head>
<body>
<form action="up.php" method="post" enctype="multipart/form-data" name="upper" >
<label for="file">Filename:</label>
<input type="file" name="file" id="file" /> 
<br />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>


Most likely, it's the PHP ini setting limiting the file upload size (upload_max_filesize).

Edit: to check this setting, you can use: echo ini_get('upload_max_filesize');. If the size in there is 52KB, then you have your answer. Actually, if it's anything less than the size of the file you want to upload, then raise it, because that will definitely become a problem somewhere down the line.


The solution is to have the file open in binary, rather than have it open in plain text mode. In your python code, replace the relevant line with:

br.form.add_file(open("tester.jpg" ,"rb"), 'image/jpeg', "tester.jpg")

The simple addition of the "rb" flag (read binary) will fix your problem. The filsize was shrunk down because it attempted to read the file normally, and uploaded only the characters that were in the ascii plain text range.

Enjoy.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜