min117の日記

初期desireもち。趣味Mac,メインFedora,仕事xp。

ChatGPT「PHPで書かれたファイルアップロードのコードを示して」

ハピタス登録で1,000円分になるURL

その買うを、もっとハッピーに。|ハピタス

 

ChatGPT完璧

すげえ

PHPで書かれたファイルアップロードのコードを示して」

<form action="upload.php" method="post" enctype="multipart/form-data">
  Select file to upload:
  <input type="file" name="fileToUpload" id="fileToUpload">
  <input type="submit" value="Upload File" name="submit">
</form>

 

<?php
if(isset($_POST['submit'])) {
  $target_dir = "uploads/";
  $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
  $uploadOk = 1;
  $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
  
  if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
      echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
  } else {
      echo "Sorry, there was an error uploading your file.";
  }
}
?>

 

複数ファイルupload対応PHP

ちゃんとfor文はさみよる。すっげえ。

PHPで書かれた複数ファイルアップロードのコードを示して」

<?php

$server_url = "http://example.com/upload.php";

if (isset($_FILES['files'])) {
    $errors = ;
    $files = $_FILES['files'];

    for ($i = 0; $i < count($files['name']); $i++) {
        $file_name = $files['name'][$i];
        $file_tmp = $files['tmp_name'][$i];
        $file_type = $files['type'][$i];
        $file_size = $files['size'][$i];
        
        if ($file_size > 2097152) {
            $errors = 'File size must be less than 2 MB';
        }

        if (empty($errors)) {
            $post_data = array(
                'file_contents' => base64_encode(file_get_contents($file_tmp)),
                'file_name' => $file_name,
                'file_type' => $file_type,
            );

            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $server_url);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

            $response = curl_exec($ch);
            curl_close($ch);

            if ($response === 'Success') {
                echo "File '$file_name' uploaded successfully<br>";
            } else {
                echo "Failed to upload file '$file_name'<br>";
            }
        } else {
            foreach ($errors as $error) {
                echo $error . "<br>";
            }
        }
    }
}

?>
<form action="" method="post" enctype="multipart/form-data">
    <input type="file" name="files" multiple>
    <input type="submit" value="Upload">
</form>

 

Ruby on Railsだとどうか

完璧

# In the controller
def create
  params[:files].each do |file|
    @upload = Upload.create(file: file)
  end
  redirect_to uploads_path
end

# In the model
class Upload < ApplicationRecord
  mount_uploader :file, FileUploader
end

# In the uploader
class FileUploader < CarrierWave::Uploader::Base
  storage :file
end

# In the view
<%= form_for @upload, url: uploads_path, html: { multipart: true } do |f| %>
  <%= file_field_tag "files", multiple: true %>
  <%= f.submit "Upload" %>
<% end %>

 

Pythonでやってみる

pythonで書かれた複数ファイルアップロードのコードを示して」

import requests

def upload_files(url, files):
    for file in files:
        with open(file, 'rb') as f:
            response = requests.post(url, files={file: f})
            if response.status_code == 200:
                print(f'File {file} was successfully uploaded.')
            else:
                print(f'File {file} was not uploaded. Response code: {response.status_code}')

files = ['file1.txt', 'file2.txt']
upload_files('http://example.com/upload', files)

 

Javaでやってみる

「javaで書かれたファイルアップロードのコードを示して」



import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

public class FileUpload {
  public static void uploadFile(String serverURL, File file) {
    try {
      String boundary = Long.toHexString(System.currentTimeMillis());
      String CRLF = "\r\n";

      URL url = new URL(serverURL);
      URLConnection connection = url.openConnection();
      HttpURLConnection httpConnection = (HttpURLConnection) connection;
      httpConnection.setUseCaches(false);
      httpConnection.setDoOutput(true);
      httpConnection.setRequestMethod("POST");
      httpConnection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

      try (OutputStream output = httpConnection.getOutputStream();
           InputStream input = new FileInputStream(file)) {
        output.write*1;
        output.write*2;
        output.write*3;
        output.write(CRLF.getBytes());

        byte buffer = new byte[4096];
        int bytesRead;
        while ((bytesRead = input.read(buffer)) != -1) {
          output.write(buffer, 0, bytesRead);
        }

        output.write((CRLF + "--" + boundary + "--" + CRLF).getBytes());
        output.flush();
      }

      int responseCode = httpConnection.getResponseCode();
      if (responseCode != HttpURLConnection.HTTP_OK) {
        throw new IOException("Server returned non-OK status: " + responseCode);
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

 

複数ファイルupload対応java

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

public class FileUpload {
  public static void uploadFiles(String serverURL, List<File> files) {
    try {
      String boundary = Long.toHexString(System.currentTimeMillis());
      String CRLF = "\r\n";

      URL url = new URL(serverURL);
      HttpURLConnection connection = (HttpURLConnection) url.openConnection();
      connection.setRequestMethod("POST");
      connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
      connection.setDoOutput(true);

      try (OutputStream output = connection.getOutputStream()) {
        for (File file : files) {
          output.write(("--" + boundary + CRLF).getBytes());
          output.write(("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\"" + CRLF).getBytes());
          output.write(("Content-Type: application/octet-stream" + CRLF + CRLF).getBytes());

          try (InputStream input = file) {
            byte buffer = new byte[1024];
            for (int length = 0; (length = input.read(buffer)) > 0;) {
              output.write(buffer, 0, length);
            }
            output.write(CRLF.getBytes());
          }
        }
        output.write*4;
      }

      if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
        System.out.println("Files uploaded successfully");
      } else {
        System.out.println("File upload failed");
      }
    } catch (IOException e) {
      System.out.println("File upload failed: " + e.getMessage());
    }
  }

  public static void main(String[] args) {
    List<File> files = new ArrayList<>();
    files.add(new File("file1.txt"));
    files.add(new File("file2.txt"));

    uploadFiles("http://example.com/upload", files);
  }
}

 

 

 

 

 

その買うを、もっとハッピーに。|ハピタス

*1:"--" + boundary + CRLF).getBytes(

*2:"Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\"" + CRLF).getBytes(

*3:"Content-Type: application/octet-stream" + CRLF).getBytes(

*4:"--" + boundary + "--" + CRLF).getBytes(