如何使用HTTP请求上传文件到服务器接口以及从服务器接口接收文件。

客户端(发送方)

使用HttpURLConnection或第三方库如Apache HttpClient、OkHttp等来发送带有文件的POST请求

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class FileUploadExample {

    public static void main(String[] args) throws IOException {
        String url = "http://your-server.com/upload"; // 服务器接口地址
        File file = new File("/path/to/your/local/file.txt"); // 要上传的文件
        
        URL obj = new URL(url);
        HttpURLConnection connection = (HttpURLConnection) obj.openConnection();
        
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW");
        
        connection.setDoOutput(true);
        DataOutputStream dos = new DataOutputStream(connection.getOutputStream());

        String boundary = "----WebKitFormBoundary7MA4YWxkTrZu0gW";
        dos.writeBytes("--" + boundary + "\r\n");
        dos.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\"\r\n");
        dos.writeBytes("Content-Type: application/octet-stream\r\n\r\n");

        InputStream fis = new FileInputStream(file);
        byte[] buffer = new byte[4096];
        int bytesRead;
        
        while ((bytesRead = fis.read(buffer)) != -1) {
            dos.write(buffer, 0, bytesRead);
        }
        
        fis.close();
        dos.writeBytes("\r\n--" + boundary + "--\r\n");
        dos.flush();
        dos.close();
        
        int responseCode = connection.getResponseCode();
        System.out.println("Response Code : " + responseCode);
    }
}
服务器端(接收方)

在服务器端,通过MultipartFile来接收文件:

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.stereotype.Controller;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

@Controller
public class FileUploadController {

    @PostMapping("/upload")
    public String handleFileUpload(@RequestParam("file") MultipartFile file) {
        if (!file.isEmpty()) {
            try {
                byte[] bytes = file.getBytes();
                File uploadDir = new File("upload-dir");
                if (!uploadDir.exists()) {
                    uploadDir.mkdir();
                }
                
                String fileName = file.getOriginalFilename();
                File serverFile = new File(uploadDir.getAbsolutePath() + "/" + fileName);
                FileOutputStream fos = new FileOutputStream(serverFile);
                fos.write(bytes);
                fos.close();
                
                return "You successfully uploaded " + fileName + "!";
            } catch (IOException e) {
                e.printStackTrace();
                return "Error during file upload!";
            }
        } else {
            return "Please select a file to upload!";
        }
    }
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值