21xrx.com
2024-12-23 03:26:33 Monday
登录
文章检索 我的文章 写文章
最近我在学习Java编程
2023-06-11 02:43:55 深夜i     --     --
上传文件 编辑文件和Java程序

最近我在学习Java编程,今天想分享一下我如何使用Java实现上传文件并能够编辑的方法。在这个过程中,我用到了三个

首先,我用Java编写了一个简单的文件上传程序。这个程序能够从用户的电脑中选取一个文件,然后将其上传到服务器上。以下是我的代码示例:


import java.io.*;

import java.net.*;

public class FileUploader {

  private static final int BUFFER_SIZE = 4096;

  public static void uploadFile(String filepath, String uploadUrl) throws IOException {

    File uploadFile = new File(filepath);

    HttpURLConnection httpConnection = (HttpURLConnection) new URL(uploadUrl).openConnection();

    httpConnection.setDoOutput(true);

    httpConnection.setRequestMethod("POST");

    httpConnection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + "===");

    OutputStream outputStream = httpConnection.getOutputStream();

    PrintWriter writer = new PrintWriter(new OutputStreamWriter(outputStream, "UTF-8"), true);

    writer.append("--===").append("\r\n");

    writer.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + uploadFile.getName() + "\"").append("\r\n");

    writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(uploadFile.getName())).append("\r\n");

    writer.append("Content-Transfer-Encoding: binary").append("\r\n");

    writer.append("\r\n");

    writer.flush();

    try (FileInputStream inputStream = new FileInputStream(uploadFile)) {

      byte[] buffer = new byte[BUFFER_SIZE];

      int bytesRead;

      while ((bytesRead = inputStream.read(buffer)) != -1) {

        outputStream.write(buffer, 0, bytesRead);

      }

      outputStream.flush();

    }

    writer.append("\r\n");

    writer.flush();

    writer.append("--===");

    writer.flush();

    int responseCode = httpConnection.getResponseCode();

    String responseMessage = httpConnection.getResponseMessage();

    System.out.println("Response status code: " + responseCode);

    System.out.println("Response message: " + responseMessage);

  }

}

接下来,我又写了一个简单的文件编辑程序。这个程序能够从服务器上读取一个文件,然后将其保存到用户的电脑上。用户可编辑这个文件并重新上传回服务器。以下是我的代码示例:


import java.io.*;

import java.net.*;

public class FileEditor {

  private static final int BUFFER_SIZE = 4096;

  public static void editFile(String fileUrl, String downloadFolder) throws IOException {

    HttpURLConnection httpConnection = (HttpURLConnection) new URL(fileUrl).openConnection();

    int responseCode = httpConnection.getResponseCode();

    if (responseCode == HttpURLConnection.HTTP_OK) {

      String disposition = httpConnection.getHeaderField("Content-Disposition");

      String contentType = httpConnection.getContentType();

      int contentLength = httpConnection.getContentLength();

      InputStream inputStream = httpConnection.getInputStream();

      String filename = disposition.substring(disposition.indexOf("filename=") + 10, disposition.length() - 1);

      String saveFilePath = downloadFolder + File.separator + filename;

      FileOutputStream outputStream = new FileOutputStream(saveFilePath);

      int bytesRead;

      byte[] buffer = new byte[BUFFER_SIZE];

      while ((bytesRead = inputStream.read(buffer)) != -1) {

        outputStream.write(buffer, 0, bytesRead);

      }

      outputStream.close();

      inputStream.close();

      // Open the file for editing

      Desktop.getDesktop().edit(new File(saveFilePath));

      // Upload the edited file

      FileUploader.uploadFile(saveFilePath, fileUrl);

    } else {

      System.out.println("No file found on server.");

    }

  }

}

最后,我将这两个程序组合在一起,实现了文件上传并能够编辑的功能。我命名为“Java实现上传文件且能编辑”的项目。在这个项目中,我编写了一个简单的用户界面,让用户选择需要上传的文件,然后上传并编辑它。以下是我的代码示例:


import javax.swing.*;

import java.awt.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.io.IOException;

public class FileUploaderEditorGUI {

  private JFrame frame;

  private JTextField textFieldFilePath;

  private JTextField textFieldFileUrl;

  private JButton btnChooseFile;

  private JButton btnUpload;

  private JButton btnEdit;

  private JPanel panel;

  public FileUploaderEditorGUI() {

    frame = new JFrame("Java实现上传文件且能编辑");

    frame.setSize(600, 350);

    frame.setResizable(false);

    frame.setLocationRelativeTo(null);

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    panel = new JPanel();

    GridBagLayout layout = new GridBagLayout();

    panel.setLayout(layout);

    GridBagConstraints constraints = new GridBagConstraints();

    constraints.fill = GridBagConstraints.HORIZONTAL;

    constraints.insets = new Insets(5, 5, 5, 5);

    JLabel labelFilePath = new JLabel("文件路径:");

    constraints.gridx = 0;

    constraints.gridy = 0;

    panel.add(labelFilePath, constraints);

    textFieldFilePath = new JTextField();

    textFieldFilePath.setEditable(false);

    constraints.gridx = 1;

    constraints.weightx = 1.0;

    panel.add(textFieldFilePath, constraints);

    btnChooseFile = new JButton("选择文件");

    btnChooseFile.addActionListener(new ActionListener() {

      @Override

      public void actionPerformed(ActionEvent e) {

        JFileChooser fileChooser = new JFileChooser();

        int returnValue = fileChooser.showOpenDialog(null);

        if (returnValue == JFileChooser.APPROVE_OPTION) {

          textFieldFilePath.setText(fileChooser.getSelectedFile().getPath());

        }

      }

    });

    constraints.gridx = 2;

    constraints.weightx = 0;

    panel.add(btnChooseFile, constraints);

    JLabel labelFileUrl = new JLabel("文件URL:");

    constraints.gridx = 0;

    constraints.gridy = 1;

    panel.add(labelFileUrl, constraints);

    textFieldFileUrl = new JTextField();

    constraints.gridx = 1;

    constraints.gridy = 1;

    constraints.gridwidth = 2;

    constraints.weightx = 1.0;

    panel.add(textFieldFileUrl, constraints);

    btnUpload = new JButton("上传文件");

    btnUpload.addActionListener(new ActionListener() {

      @Override

      public void actionPerformed(ActionEvent e) {

        try {

          FileUploader.uploadFile(textFieldFilePath.getText(), textFieldFileUrl.getText());

        } catch (IOException ex) {

          ex.printStackTrace();

        }

      }

    });

    constraints.gridx = 0;

    constraints.gridy = 2;

    constraints.gridwidth = 2;

    constraints.weightx = 1.0;

    panel.add(btnUpload, constraints);

    btnEdit = new JButton("编辑文件");

    btnEdit.addActionListener(new ActionListener() {

      @Override

      public void actionPerformed(ActionEvent e) {

        try {

          FileEditor.editFile(textFieldFileUrl.getText(), System.getProperty("user.home"));

        } catch (IOException ex) {

          ex.printStackTrace();

        }

      }

    });

    constraints.gridx = 2;

    constraints.gridy = 2;

    constraints.gridwidth = 1;

    constraints.weightx = 0;

    panel.add(btnEdit, constraints);

    frame.getContentPane().add(panel);

    frame.setVisible(true);

  }

  public static void main(String[] args) {

    new FileUploaderEditorGUI();

  }

}

我成功地用Java实现了上传文件并能够编辑的功能,这给我带来了很多的乐趣和挑战。我相信这个过程也会对Java编程的学习者们有所启发。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复
    相似文章