doulaopu2343
doulaopu2343
2016-03-16 08:34

通过PHP [CodenameOne]在服务器上上传文件

I want to upload image file on server, because not found any way to upload file directly on server from CodenameOne. I convert image in Base64 format and send to php file then in php again decode image and tried to upload. But same also not working. Can you please tell me how do i solve this problem ?

My PHP Code :

<?php

define('UPLOAD_DIR', 'public_html/appFiles/GKQuiz/userProfilePicture/');
//$Imagecode=$_POST['Image'];


//Base64 String already added in $Imagecode
$Imagecode="/9j/4AAQSkZJRgABAgAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAARCABAAEADASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAP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GdpyBHI6hvrknP8An61zzMCQ6oUGOhPX9PSgMUG3GP8AdIz9atTktmQ4piJxjcRkdD6Uu4rhmJJxtyTjt0xTTlifkOM4yOSMf/WpYbeSbaiEhXbGSOOlTexSV9hyyRliXAOO2euOlXBbzWQWVANyqDyOmcj8Dz2qSytbeNA7yp5/AAyQF5zuyO449e/oM22t/tjeY7PsG1c5w20A5wMjJ6DNYyq2fkbRpXXmZsTxxCUM6uzpnGM4+h9ec+nHrUNxDLFKEVzIwAJw3cjPH+NT3FtMYGvImxAcLgvlj6ZHfp9Pl9qqCdo4niJJJYZ59M/4mtE77GTVtx5uY1EexPLdBgkHduOTyCenYfhmpYxHJIFEgaPJPGQW9BgDOTjjsMj3quwWVUJUbjxwep9sf1pjQyKgbDFV49h1/wD11VhXP//Z";

$img=base64_decode($Imagecode);
//echo $img;
$uid=uniqid();

$ftp_server = "example.com";
$ftp_conn = ftp_connect($ftp_server) or die("Could not connect to ftp_server");
$login = ftp_login($ftp_conn, "example.com", "123");

if (ftp_put($ftp_conn, UPLOAD_DIR . $uid . ".jpg", $img, FTP_BINARY))
{
  echo "Successfully uploaded";
}
else{
  echo "Error uploading";
}

// close connection
ftp_close($ftp_conn);

?>
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

3条回答

  • dongyou6909 dongyou6909 5年前

    Finally the found answer for same as below.

    Corrected PHP Code :

    <?php
    
    define('UPLOAD_DIR',$_SERVER['DOCUMENT_ROOT'].'/appFiles/GKQuiz/userProfilePicture/');
    
    // after $_SERVER['DOCUMENT_ROOT']. your root inside public_html folder if any or '/'.
    
    $Imagecode=$_POST['Image']; // parameter
    
    $img=base64_decode($Imagecode);
    $uid=uniqid();
    
    $file = UPLOAD_DIR . $uid . '.jpg';
    $success = file_put_contents($file, $img);
    
    if ($success)
    {
      echo $uid.'.jpg';
    }
    else
    {
      echo "error";
    }
    
    ?>
    

    In CodenameOne your code may be as below :

    if (profilepic!=null) {
    ImageIO imgIO = ImageIO.getImageIO();
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    imgIO.save(profilepic, out, ImageIO.FORMAT_JPEG, 1);
    byte[] ba = out.toByteArray();
    String Imagecode = Base64.encode(ba);
    //System.out.println("data :"+Imagecode);
    request = new ConnectionRequest(){
         @Override
         protected void handleErrorResponseCode(int code, String message) {
               System.out.println("Code :"+code+" Msg :"+message);
         }
    
    };
    request.setPost(true);
    request.setHttpMethod("POST");
    request.addArgument("Image", Imagecode);
    request.setUrl("http://example.com/filename.php");
    NetworkManager.getInstance().addToQueueAndWait(request);
    }else{
         System.out.println("Unable to upload");
    }
    
    点赞 评论 复制链接分享
  • dpxbc88022 dpxbc88022 5年前

    Codename One has a builtin standard upload API thru support for the multipart request HTTP standard in MultipartRequest.

    MultipartRequest seamlessly handles the binary base64 etc.

    MultipartRequest request = new MultipartRequest();
    request.setUrl(url);
    request.addData("myFileName", fullPathToFile, "text/plain")
    NetworkManager.getInstance().addToQueue(request);
    

    Java servlet code to intercept this should look like that:

    @WebServlet(name = "UploadServlet", urlPatterns = {"/upload"})
    @MultipartConfig(fileSizeThreshold = 1024 * 1024 * 100, // 10 MB
            maxFileSize = 1024 * 1024 * 150, // 50 MB
            maxRequestSize = 1024 * 1024 * 200)      // 100 MB
    public class UploadServlet extends HttpServlet {
    
        @Override
        public void doPost(HttpServletRequest req, HttpServletResponse res)
                throws ServletException, IOException {
            Collection<Part> parts = req.getParts();
            Part data = parts.iterator().next();
            try(InputStream is = data.getInputStream()) {}
                // store or do something with the input stream
            }
        }
    }
    

    I'm not a PHP guy but a quick google search landed me on w3c school with this

    <?php
    $target_dir = "uploads/";
    $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
    $uploadOk = 1;
    $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
    // Check if image file is a actual image or fake image
    if(isset($_POST["submit"])) {
        $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
        if($check !== false) {
            echo "File is an image - " . $check["mime"] . ".";
            $uploadOk = 1;
        } else {
            echo "File is not an image.";
            $uploadOk = 0;
        }
    }
    ?> 
    
    点赞 评论 复制链接分享
  • doushao5047 doushao5047 5年前

    I guess you need to use PHP: move_uploaded_file() As you can see here is a full example, hope it helps you.

    点赞 评论 复制链接分享