저지 파일 업로드 서비스를 만드는 데 문제가 있습니다.저지 : MultiPart 양식 파일 업로드 지원되지 않는 미디어 유형 (415)
사양은 다음과 같습니다. 서버는 클라이언트가 GET
방법을 사용하여 파일에 액세스 할 수있게합니다. index.html
을 사용하면 복수 파트 양식 Data Handler를 사용하여 복수 파일을 POST
까지 작성할 수 있습니다.
그러나 CSV 파일 (Content-Type: text/csv
)을 업로드하려고하면 서버가 즉시 415 오류로 응답하고 처리기 메서드 코드를 입력하거나 오류를 내뱉지 않습니다. 당신의 도움에 미리
@Path("/ui/")
public class HtmlServer {
static final Logger LOGGER = Logger.getLogger(HtmlServer.class.getCanonicalName());
@GET
@Path("/{file}")
@Produces(MediaType.TEXT_HTML)
public Response request(@PathParam("file") @DefaultValue("index.html") String path) {
LOGGER.info("HTTP GET /ui/" + path);
String data;
try {
if ("".equals(path))
data = getFileBytes("web/index.html");
else
data = getFileBytes("web/" + path);
return Response.ok(data, MediaType.TEXT_HTML).build();
} catch (IOException e) {
e.printStackTrace();
return Response.ok("<h1>Server error</h1>", MediaType.TEXT_HTML).build();
}
}
@POST
@Path("/{file}")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFiles(final FormDataMultiPart multiPart) {
List<FormDataBodyPart> bodyParts = multiPart.getFields("dataset");
StringBuffer fileDetails = new StringBuffer("");
/* Save multiple files */
for (int i = 0; i < bodyParts.size(); i++) {
BodyPartEntity bodyPartEntity = (BodyPartEntity) bodyParts.get(i).getEntity();
String fileName = bodyParts.get(i).getContentDisposition().getFileName();
saveToFile(bodyPartEntity.getInputStream(), "/.../" + fileName);
fileDetails.append(" File saved to /.../" + fileName);
}
System.out.println(fileDetails);
return Response.ok(fileDetails.toString()).build();
}
private static String getFileBytes(String path) throws IOException {
byte[] bytes = Files.toByteArray(new File(path));
return new String(bytes);
}
private static void saveToFile(InputStream uploadedInputStream, String uploadedFileLocation) {
try {
OutputStream out = null;
int read = 0;
byte[] bytes = new byte[1024];
out = new FileOutputStream(new File(uploadedFileLocation));
while ((read = uploadedInputStream.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
감사 :
여기 내 코드입니다!
나는'enctype = "multipart/form-data"를 사용하여 죽은 간단한 html 폼을 통해 API를 테스트하고있다. –