1.创建上传文件接口
备注: 使用jersey框架文章来源:https://www.toymoban.com/news/detail-507610.html
@Path("/upload")
@Controller
public class UploadFileController {
@Path("/files")
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
public Response uploadFiles2(@FormDataParam("data") String data,
@FormDataParam("files") List<FormDataBodyPart> bodyParts,
@FormDataParam("files") FormDataContentDisposition fileDispositions,
@FormDataParam("file") InputStream fileInputStream,
@FormDataParam("file") FormDataContentDisposition fileDisposition) {
// 处理多文件
for(FormDataBodyPart fdsp: bodyParts) {
BodyPartEntity bodyPartEntity = (BodyPartEntity) fdsp.getEntity();
String fileName = bodyParts.get(i).getContentDisposition().getFileName();
InputStream inputStream = bodyPartEntity.getInputStream();
//TODO 处理文件
}
// 处理单文件
// 根据fileInputStream输入流处理单文件内容
return "OK";
}
}
2.前端代码调用上传文件接口
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>上传文件前端代码</title>
</head>
<body>
<h2>上传文件</h2>
<form action="/upload/files" enctype="multipart/form-data" method="post">
<label>选择多文件上传</label><input type= "file" name="files" multiple /> <br/><br/>
<label>选择单文件上传</label><input type= "file" name="file" /> <br/><br/>
<label>其他参数</label> <input name="data" maxlength="100"/> <br/><br/>
<input type="submit" title="上传"/>
</form>
</body>
</html>
2.后端调用上传文件接口
2.1.使用HttpURLConnection上传文件
2.1.1.上传本地文件
参考链接: Jersey (JAX-RS) multiple files upload example文章来源地址https://www.toymoban.com/news/detail-507610.html
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;
public class HttpPostMultipart {
private final String boundary;
private static final String LINE = "\r\n";
private HttpURLConnection httpConn;
private String charset;
private OutputStream outputStream;
private PrintWriter writer;
public HttpPostMultipart(String requestURL, String charset, Map<String, String> headers) throws IOException {
this.charset = charset;
boundary = UUID.randomUUID().toString();
URL url = new URL(requestURL);
httpConn = (HttpURLConnection) url.openConnection();
httpConn.setUseCaches(false);
httpConn.setDoOutput(true);
httpConn.setDoInput(true);
httpConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
if (headers != null && headers.size() > 0) {
Iterator<String> it = headers.keySet().iterator();
while (it.hasNext()) {
String key = it.next();
String value = headers.get(key);
httpConn.setRequestProperty(key, value);
}
}
outputStream = httpConn.getOutputStream();
writer = new PrintWriter(new OutputStreamWriter(outputStream, charset), true);
}
public void addFormField(String name, String value) {
writer.append("--" + boundary).append(LINE);
writer.append("Content-Disposition: form-data; name=\"" + name + "\"").append(LINE);
writer.append("Content-Type: text/plain; charset=" + charset).append(LINE);
writer.append(LINE);
writer.append(value).append(LINE);
writer.flush();
}
public void addFilePartLocalFile(String fieldName, File uploadFile)
throws IOException {
String fileName = uploadFile.getName();
writer.append("--" + boundary).append(LINE);
writer.append("Content-Disposition: form-data; name=\"" + fieldName + "\"; filename=\"" + fileName + "\"").append(LINE);
writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(fileName)).append(LINE);
writer.append("Content-Transfer-Encoding: binary").append(LINE);
writer.append(LINE);
writer.flush();
FileInputStream inputStream = new FileInputStream(uploadFile);
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.flush();
inputStream.close();
writer.append(LINE);
writer.flush();
}
/**
* 上传内容
*/
public void addFilePartContent(String fieldName, String fileName, String content)
throws IOException {
writer.append("--" + boundary).append(LINE);
writer.append("Content-Disposition: form-data; name=\"" + fieldName + "\"; filename=\"" + fileName + "\"").append(LINE);
writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(fileName)).append(LINE);
writer.append("Content-Transfer-Encoding: binary").append(LINE);
writer.append(LINE);
writer.flush();
writer.append(content);
writer.append(LINE);
writer.flush();
}
public String finish() throws IOException {
String response = "";
writer.flush();
writer.append("--" + boundary + "--").append(LINE);
writer.close();
int status = httpConn.getResponseCode();
if (status == HttpURLConnection.HTTP_OK) {
ByteArrayOutputStream result = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = httpConn.getInputStream().read(buffer)) != -1) {
result.write(buffer, 0, length);
}
response = result.toString(this.charset);
httpConn.disconnect();
} else {
throw new IOException("Server returned non-OK status: " + status);
}
return response;
}
public static void testUploadFileLocalFile() {
try {
// 设置header, 里面可以放权限Authorization
Map<String, String> headers = new HashMap<>();
headers.put("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36");
HttpPostMultipart multipart = new HttpPostMultipart("http://localhost:8080/upload/files", "utf-8", headers);
multipart.addFormField("data", "1234567");
multipart.addFilePart("file", new File("/home/user/test.png"));
System.out.println(multipart.finish());
} catch (Exception e) {
e.printStackTrace();
}
}
public static void testUploadFileContent() {
try {
// 设置header, 里面可以放权限Authorization
Map<String, String> headers = new HashMap<>();
headers.put("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36");
HttpPostMultipart multipart = new HttpPostMultipart("http://localhost:8080/upload/files", "utf-8", headers);
multipart.addFormField("data", "1234567");
multipart.addFilePartContent("file", "test.xml", "<?xml version=\"1.0\" encoding=\"UTF-8\"?><test name=\"test\" value=\"1\"></test>"));
System.out.println(multipart.finish());
} catch (Exception e) {
e.printStackTrace();
}
}
// 测试上传
public static void main(String[] args) {
//测试上传本地文件
testUploadFileLocalFile();
//测试上传文件具体内容
testUploadFileContent();
}
}
到了这里,关于java创建上传文件接口并使用HTTP测试的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!