在Java中我们需要模拟页面的请求,实现上传表单的功能,具体操作如下
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.UUID;
/**
* @author Philip Lee
* @date 2023/3/6 10:40
* 发送网络上传文件请求
*/
public class FileUploadTool {
private static final Logger log = LoggerFactory.getLogger(FileUploadTool.class);
public static String sendPostWithFile(String url, File file) {
log.info("Get a request to upload file. What fileName is {}", file.getName());
DataOutputStream outputStream = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
//打开和URL之间的连接
HttpURLConnection httpURLConnection = (HttpURLConnection) realUrl.openConnection();
//设置POST请求必须设置如下两行
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
String BOUNDARY = UUID.randomUUID().toString();
httpURLConnection.setUseCaches(false);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("connection", "Keep-Alive");
httpURLConnection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
httpURLConnection.setRequestProperty("Charset", "UTF-8");
httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
httpURLConnection.connect();
outputStream = new DataOutputStream(httpURLConnection.getOutputStream());
byte[] end_data = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
//添加参数 "type":"keepFiles"
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("--");
stringBuilder.append("--");
stringBuilder.append(BOUNDARY);
stringBuilder.append("\r\n");
stringBuilder.append("Content-Disposition: form-data; name=\"type\"");
stringBuilder.append("\r\n");
stringBuilder.append("\r\n");
stringBuilder.append("keepFiles");
stringBuilder.append("\r\n");
outputStream.write(stringBuilder.toString().getBytes());
//添加文件file,对应后端controller中的file key值
StringBuilder sb = new StringBuilder();
sb.append("--");
sb.append(BOUNDARY);
sb.append("\r\n");
sb.append("Content-Disposition: form-data; name=\"file\";filename=\"" + file.getName() + "\"");
sb.append("\r\n");
sb.append("Content-Type: application/octet-stream");
sb.append("\r\n");
sb.append("\r\n");
outputStream.write(sb.toString().getBytes());
DataInputStream in1 = new DataInputStream(new FileInputStream(file));
int bytes = 0;
byte[] bufferOut = new byte[1024];
while ((bytes = in1.read(bufferOut)) != -1) {
outputStream.write(bufferOut, 0, bytes);
}
//多个文件时,两个文件之间加入下面这行代码,如有必要重新创建一个StringBuilder,重复上面的步骤
outputStream.write("\r\n".getBytes());
in1.close();
outputStream.write(end_data);
//刷新输出流的缓冲
outputStream.flush();
//定义BufferedReader输出流来读取URL的响应
in = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
//
e.printStackTrace();
} finally {
try {
if (outputStream != null) {
outputStream.close();
}
if (in != null) {
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
log.info("Upload file end, Result is {}", result);
return result;
}
}
以上模拟浏览器发送请求的的参数和文件需要对应controller中的@RequestParam(name = "***")
我的Server端Controller 层如下:
@ApiOperation(value = "上传文件", notes = "上传文件到服务器")
@ApiImplicitParams(value = {
@ApiImplicitParam(name = "file", value = "文件", dataTypeClass = MultipartFile.class),
@ApiImplicitParam(name = "type", value = "上传类型(我是功能是上传的图片有不同的来源,作用也不同)", dataTypeClass = String.class),
})
@PostMapping
public RespModel<String> uploadFiles(@RequestParam(name = "file") MultipartFile file,
@RequestParam(name = "type") String type) throws IOException {
*************
}
分别为 file 和 type