java写一个上传文件的方法
时间: 2024-02-03 11:01:46 浏览: 158
以下是一个简单的Java上传文件方法:
```java
public void uploadFile(File file) throws IOException {
String url = "http://example.com/upload"; // 上传文件的URL
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
MultipartEntity multipartEntity = new MultipartEntity();
multipartEntity.addPart("file", new FileBody(file));
httpPost.setEntity(multipartEntity);
HttpResponse response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
throw new IOException("上传文件失败,HTTP响应状态码:" + statusCode);
}
}
```
使用Apache HttpClient库,将文件上传至指定的URL。在这个例子中,上传的文件名为“file”,文件体为FileBody对象。如果HTTP响应状态码不是200,将会抛出IOException异常。
阅读全文