通过WebService

时间:2018-02-05 09:35:47

标签: java rest web-services jax-rs

我实施了一个REST网络服务,用于将文件上传到我的服务器:

@Path("/upload")
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_XML)
public javax.ws.rs.core.Response uploadNewAdvJson(@FormDataParam("file") InputStream is) {

    boolean res = true;
    OutputStream out = null;
    try {

        File directory = new File("myFolder");
        if (!directory.exists()) {
            directory.mkdirs();
        }

        out = new FileOutputStream(new File("myFolder" + File.separator + "myFile.png"));
        int read = 0;
        byte[] bytes = new byte[1024];

        while ((read = is.read(bytes)) != -1) {
            out.write(bytes, 0, read);
        }
        out.flush();
        out.close();
    } catch (IOException e) {
        e.printStackTrace();
        res = false;
        if (out != null) {
            try {
                out.close();
                out.flush();
            } catch (IOException e1) {
                // do nothing
            }
        }
    }

    return new Response();
}

(其中Response是我的JAXB响应对象)。

我正在使用此客户端测试此服务:

public class Test {

public static void main(String[] args) {
     final Client client = ClientBuilder.newBuilder().register(MultiPartFeature.class).build();

        final FileDataBodyPart filePart = new FileDataBodyPart("file", new File("pathToImage/imgToUpload.png");
        FormDataMultiPart formDataMultiPart = new FormDataMultiPart();
        final FormDataMultiPart multipart = (FormDataMultiPart) formDataMultiPart.field("foo", "bar").bodyPart(filePart);

        final WebTarget target = client.target("http://localhost:8080/myServer/rest/uploadNewAdv");
        final Response response = target.request().post(Entity.entity(multipart, multipart.getMediaType()));             
        try {
            formDataMultiPart.close();
            multipart.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

但它并没有像我期望的那样奏效。实际上,创建并保存了myFile.png,但其大小与imageToUpload.png不同,我无法将其作为图像打开(看起来像一个损坏的文件)。 怎么了?

0 个答案:

没有答案