gpt4 book ai didi

java - png 文件 上传 Restful Web 服务 java

转载 作者:行者123 更新时间:2023-11-30 07:51:29 25 4
gpt4 key购买 nike

我尝试为我的网络服务编写一个图像文件上传 post 方法。这是我的发帖方法。图片文件可以通过post方法上传,但不能转换为Image类型。

@POST
@Path("/upload")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces("text/html")
public Response uploadFile(@FormDataParam("file") File file2) throws IOException {
InputStream IS = null;

String output = "";

try {
IS = new FileInputStream(file2);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {

}


try {
if (file2 != null && IS != null) {
Image img = ImageIO.read(IS);
if (img != null) {
output = "image file transmission sucessed";

} else {
String out = convertStreamToString(IS);
output = "file uploaded into post method, however can not transfer it into image type "+
"\n"+ out;
}

} else if (file2 == null) {
output = "the file uploaded into post method is null";
}

} catch (IOException e) {
e.printStackTrace();

}

return Response.status(200).entity(output).build();

}

static String convertStreamToString(java.io.InputStream is) {
java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}

“文件已上传到post方法中,但无法将其转为图像类型“+”\n”+ out;显示消息。我相信的原因是 inputStream 包含额外的文件信息+图像的内容。当我尝试将 inputStream 转换回 Image 时,我需要找到一种方法来摆脱传递的额外信息。

这是我的新版本:

@POST
@Path("/images")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response imageUpload(
@FormDataParam("image") InputStream hereIsImage,
@FormDataParam("image") FormDataContentDisposition hereIsName) {
String path = "f://";
if (hereIsName.getSize() == 0) {
return Response.status(500).entity("image parameter is missing")
.build();
}
String name = hereIsName.getFileName();
path += name;

try {
OutputStream out = new FileOutputStream(new File(path));
int read;
byte[] bytes = new byte[1024];
while ((read = hereIsImage.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
out.flush();
out.close();
} catch (IOException e) {
return Response.status(500)
.entity(name + " was not uploaded\n" + e.getMessage())
.build();
}
return Response.status(200).entity(name + " was uploaded").build();
}

但是,当我上传图片时,会弹出错误:

[ERROR] An exception occurred during processing of the au.edu.rmit.srtwebservice.util.rest.testWS class. This class is ignored. com/sun/jersey/core/header/FormDataContentDisposition

testWS.calss 是我的方法所在的位置。

最佳答案

public Response uploadFile(@FormDataParam("file") File file2)

File 输入可能不起作用,因为您很可能从客户端发送八位字节流。因此,尝试使用 InputStream 作为输入类型,希望它能够工作。

public Response uploadFile(@FormDataParam("file") InputStream file2)

关于java - png 文件 上传 Restful Web 服务 java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33295268/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com