Java写一段附件上传
时间: 2023-09-25 16:06:18 浏览: 95
这里是Java写一段附件上传的示例代码:
```
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.UUID;
public class FileUploader {
private static final String BOUNDARY = "---------------------------" + UUID.randomUUID().toString().replaceAll("-", "");
public static void main(String[] args) throws IOException {
File file = new File("path/to/file");
String url = "http://example.com/upload";
String contentType = "application/octet-stream";
upload(file, url, contentType);
}
public static void upload(File file, String url, String contentType) throws IOException {
HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
String fileName = file.getName();
String fieldName = "file";
StringBuilder sb = new StringBuilder();
sb.append("--").append(BOUNDARY).append("\r\n")
.append("Content-Disposition: form-data; name=\"").append(fieldName).append("\"; filename=\"").append(fileName).append("\"\r\n")
.append("Content-Type: ").append(contentType).append("\r\n")
.append("\r\n");
byte[] headerBytes = sb.toString().getBytes();
InputStream is = new FileInputStream(file);
byte[] dataBytes = is.readAllBytes();
byte[] footerBytes = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
conn.setRequestProperty("Content-Length", String.valueOf(headerBytes.length + dataBytes.length + footerBytes.length));
conn.getOutputStream().write(headerBytes);
conn.getOutputStream().write(dataBytes);
conn.getOutputStream().write(footerBytes);
int responseCode = conn.getResponseCode();
System.out.println("Response code: " + responseCode);
}
}
```
使用时,需要替换以下部分:
- `path/to/file`:文件路径
- `http://example.com/upload`:上传接口地址
- `application/octet-stream`:文件类型
该代码使用`HttpURLConnection`发送POST请求,将文件作为multipart/form-data形式的请求体发送。请求体的格式如下:
```
--boundary
Content-Disposition: form-data; name="field_name"; filename="file_name"
Content-Type: content_type
file_data
--boundary--
```
其中,`boundary`为随机生成的字符串,用于分隔请求体的各个部分;`field_name`为文件字段名,可以自定义;`file_name`为文件名;`content_type`为文件类型,根据实际情况设置;`file_data`为文件内容。最后,需要计算请求体的长度,并设置`Content-Length`请求头。上传完成后,可以根据响应码判断上传是否成功。
阅读全文