淘先锋技术网

首页 1 2 3 4 5 6 7

Java中,通过使用multipart/form-data协议可以上传文件以及其他表单字段。在这种情况下,表单数据被划分为多个部分,并通过HttpURLConnection类的POST方法发送。

以下是一个处理multipart/form-data请求的Java示例:

public boolean uploadFile(String serverUrl, String filePath, String fieldName) {
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
String fileName = filePath.substring(filePath.lastIndexOf("/") + 1);
String boundary = "****************";
try {
URL url = new URL(serverUrl);
connection = (HttpURLConnection) url.openConnection();
//固定参数,可参考RFC1867协议
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
outputStream = new DataOutputStream(connection.getOutputStream());
//处理上传文件
outputStream.writeBytes("--" + boundary + "\r\n");
outputStream.writeBytes("Content-Disposition: form-data; name=\"" + fieldName + "\"; filename=\"" + fileName + "\"\r\n");
outputStream.writeBytes("Content-Type:application/octet-stream\r\n\r\n");
FileInputStream fileInputStream = new FileInputStream(new File(filePath));
int bytesRead, bufferSize;
byte[] buffer = new byte[8192];
while ((bytesRead = fileInputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.writeBytes("\r\n");
fileInputStream.close();
//处理其他表单字段
outputStream.writeBytes("--" + boundary + "\r\n");
outputStream.writeBytes("Content-Disposition: form-data; name=\"name\"" + "\r\n");
outputStream.writeBytes("\r\n");
outputStream.writeBytes("John Smith\r\n");
outputStream.writeBytes("--" + boundary + "--\r\n");
outputStream.flush();
outputStream.close();
//读取响应数据
InputStream inputStream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
StringBuffer response = new StringBuffer();
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
return true;
} catch (Exception e) {
return false;
} finally {
if (connection != null) {
connection.disconnect();
}
}
}