HTTP文件上传实例

本文介绍了在HTTP文件上传过程中,为何选择POST请求而非GET请求,主要原因是POST请求的参数大小不受限,适合二进制流传输。同时,提到了在实现文件上传时需要导入Apache的commons-fileupload-1.3.2.jar和commons-io-2.5.jar库。
摘要由CSDN通过智能技术生成

一。上传文件需要导入两个开源包,可在commons.apache.org中下载,包为commons-fileupload-1.3.2.jar    commons-io-2.5.jar  。由于get请求参数大小有限制(get请求参数放在url地址内,而url地址的大小有限制)而post请求的请求参数放在请求正文内,故请求参数大小无限制,并且post请求能进行二进制流传输,故在文件上传时需要用post请求。


二。上传文件的jsp界面代码:

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<form action="UploadServlet" method="post" enctype="multipart/form-data">
		<h2>文件上传,图片上传测试</h2>
		输入框测试:<
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的 Java HttpPost 上传文件的示例: ```java import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.mime.HttpMultipartMode; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.entity.mime.content.FileBody; import org.apache.http.impl.client.HttpClientBuilder; import java.io.File; import java.io.IOException; public class FileUploader { public static void main(String[] args) throws IOException { String url = "http://localhost:8080/upload"; String filePath = "/path/to/file.txt"; HttpClient httpClient = HttpClientBuilder.create().build(); HttpPost httpPost = new HttpPost(url); File fileToUpload = new File(filePath); FileBody fileBody = new FileBody(fileToUpload); HttpEntity entity = MultipartEntityBuilder.create() .setMode(HttpMultipartMode.BROWSER_COMPATIBLE) .addPart("file", fileBody) .build(); httpPost.setEntity(entity); HttpResponse httpResponse = httpClient.execute(httpPost); System.out.println("Response Code : " + httpResponse.getStatusLine().getStatusCode()); } } ``` 在此示例中,我们使用 Apache HttpClient 库来构建 HttpPost 请求并上传文件。我们首先创建一个 HttpClient 实例,然后创建一个 HttpPost 实例,并指定要上传到的 URL。接下来,我们使用 FileBody 类创建一个文件主体,然后使用 MultipartEntityBuilder 类创建一个包含文件主体的多部分实体。最后,我们将实体设置为 HttpPost 对象的实体,并执行请求。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值