背景:

     最近在做数据对接方面的工作,其中有一个需求是将我们公司以 blob 形式存储在数据库中的文件读出来访问要对接公司的文件上传接口,将这些文件对接到对方公司,记录一下 Java 发送文件上传请求的代码。先贴出要访问的接口代码:

@RequestMapping(method = RequestMethod.POST, value = "/upload")
@ApiOperation(value = "表单文件上传")
@ApiImplicitParam(name = "file", value = "file", required = true, dataType = "MultipartFile", paramType = "form")
public ResponseResult upload(@RequestParam("file") @NotNull(message = "上传文件不能为空") MultipartFile file) {
String fileId = fileService.uploadFile(file);
return ResponseResult.success(fileId);
}

     从这个接口可以看到我们要模拟 form 表单文件上传。下面是 java 代码模拟发送这个文件上传请求。

代码:

public String fileUploadPost(byte[] fileContent, String fileName) {
String end = "\r\n";
String twoHyphens = "--";
String boundary = "*****";

String result = "";
try {
URL url = new URL("http://192.168.10.75:16002/api/upload");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
/* 允许Input、Output,不使用Cache */
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);
/* 设置传送的method=POST */
con.setRequestMethod("POST");
/* setRequestProperty */
con.setRequestProperty("Connection", "Keep-Alive");
con.setRequestProperty("Charset", "UTF-8");
con.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
/* 设置DataOutputStream */
DataOutputStream ds = new DataOutputStream(con.getOutputStream());
ds.writeBytes(twoHyphens + boundary + end);
ds.writeBytes("Content-Disposition: form-data; "
+ "name=\"file\";filename=\"" + fileName + "\"" + end);
ds.writeBytes(end);
// byte 转 file

/* 取得文件的FileInputStream */
DataInputStream in = new DataInputStream(new ByteArrayInputStream(fileContent));
/* 设置每次写入1024bytes */
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int length = -1;
/* 从文件读取数据至缓冲区 */
while ((length = in.read(buffer)) != -1) {
/* 将资料写入DataOutputStream中 */
ds.write(buffer, 0, length);
}
ds.writeBytes(end);
ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
/* close streams */
in.close();
ds.flush();

int resultCode = con.getResponseCode();
if (resultCode == HttpURLConnection.HTTP_OK) {
InputStream is = con.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line;
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line);
}
reader.close();
is.close();
result = sb.toString();
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}

  这个 fileContent 参数就是一个 byte[] 类型的,是使用 JDBCTemplate 这样从数据库中读出来的:

String sql = "select file_content from filecontent where file_content_id= ?";
Object[] params = {fileId};
Blob blob = jdbcTemplate.queryForObject(sql, params, Blob.class);
int length = (int) blob.length();
return blob.getBytes(1, length);