21xrx.com
2024-09-19 10:06:21 Thursday
登录
文章检索 我的文章 写文章
最近我在学习Java网络编程
2023-06-10 08:42:05 深夜i     --     --

最近我在学习Java网络编程,其中涉及到了文件上传的问题。经过查阅相关资料和尝试,我总结了一些Java实现文件上传的方式,并在此分享给大家。

1.使用HttpURLConnection方式上传文件

HttpURLConnection是Java标准库中的一个类,可以用来模拟HTTP连接进行网络编程。以下是使用HttpURLConnection上传文件的实现代码:


//创建连接

URL url = new URL(uploadUrl);

HttpURLConnection conn = (HttpURLConnection) url.openConnection();

//设置参数

conn.setDoOutput(true);

conn.setUseCaches(false);

conn.setRequestMethod("POST");

//设置请求头

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

//上传文件

DataOutputStream out = new DataOutputStream(conn.getOutputStream());

out.writeBytes("--" + boundary + "\r\n");

out.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\"" + fileName + "\"\r\n");

out.writeBytes("Content-Type: application/octet-stream\r\n\r\n");

byte[] buffer = new byte[1024 * 10];

int len = 0;

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

  out.write(buffer, 0, len);

}

out.write("\r\n--" + boundary + "--\r\n".getBytes());

out.flush();

//获取响应

int respCode = conn.getResponseCode();

if (respCode == HttpURLConnection.HTTP_OK) {

  BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

  String line;

  while ((line = reader.readLine()) != null) {

    System.out.println(line);

  }

}

这段代码中,要特别注意的是设置请求头的Content-Type为multipart/form-data类型,表示上传的是二进制文件数据。同时,需要在HTTP协议中添加一个边界分割符用于分隔上传数据。在上传时,使用DataOutputStream写入请求数据到输出流中。最后,根据服务器的响应状态判断文件上传的结果。

2.使用Apache HttpClient方式上传文件

Apache HttpClient是一个开源的Java HTTP客户端库,可以用于发送HTTP请求。以下是使用Apache HttpClient上传文件的实现代码:


CloseableHttpClient httpClient = HttpClients.createDefault();

HttpPost httpPost = new HttpPost(uploadUrl);

MultipartEntityBuilder builder = MultipartEntityBuilder.create();

//上传文件

builder.addBinaryBody("file", file, ContentType.APPLICATION_OCTET_STREAM, fileName);

HttpEntity multipart = builder.build();

httpPost.setEntity(multipart);

//发送请求

CloseableHttpResponse response = httpClient.execute(httpPost);

//获取响应

int statusCode = response.getStatusLine().getStatusCode();

if (statusCode == HttpStatus.SC_OK) {

  HttpEntity responseEntity = response.getEntity();

  //读取响应数据

  String responseBody = EntityUtils.toString(responseEntity, "utf-8");

  System.out.println(responseBody);

}

response.close();

httpClient.close();

这段代码中,使用MultipartEntityBuilder创建一个多部分实体(MultipartEntity)来上传文件。然后使用HttpPost发送HTTP请求,并将多部分实体设置为请求实体。结果根据HTTP响应状态码判断文件上传是否成功。

3.使用SpringMVC方式上传文件

SpringMVC是基于Spring框架的MVC设计模式的Web应用框架,可以很方便地实现文件上传功能。以下是使用SpringMVC上传文件的实现代码:


@RequestMapping(value = "/upload", method = RequestMethod.POST)

@ResponseBody

public String upload(@RequestParam("file") MultipartFile file) throws IOException {

  //上传文件

  String fileName = file.getOriginalFilename();

  file.transferTo(new File(uploadDir, fileName));

  return "success";

}

这段代码中,使用@RequestParam注解获取请求参数file,它是一个类型为MultipartFile的对象。然后调用MultipartFile的transferTo方法将文件保存到指定的目录。最后,返回上传成功的信息给客户端。

综上所述,Java实现文件上传的方式有多种,每种方式都有其优点和缺点。要根据实际需求选择适合的方式来实现文件上传功能。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复