3

我正在使用 Jersey 开发一个休息服务器。我需要制作一个 API,将图像上传到服务器上的文件夹中。我的 API 必须包含 2 个参数。一个字符串参数和一个文件参数。

@POST
@Path("path")
@public Response uploadImage(@FormParam("name") String name, @FormDataParam("imagestream") InputStream imageStream)

如果我从客户端应用程序发送 2 个参数,我将无法接收这两个属性。

我的客户端代码如下:

private static void instantiateConnection(String urlString, byte[] params)
{
    HttpURLConnection conn = null;

    try
    {
        URL url = new URL(urlString);

        conn = (HttpURLConnection) url.openConnection();

        outStream(conn, params);

        int responseCode = conn.getResponseCode();

        if (responseCode == HttpURLConnection.HTTP_OK)
        {
            InputStream instream = conn.getInputStream();

            instream.close();
        }

    }
    catch (MalformedURLException e)
    {
        e.printStackTrace();
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }
    finally
    {
        conn.disconnect();
    }
}

private static void outStream(HttpURLConnection conn, byte[] param)
{
    String name = new String("name");

    conn.addRequestProperty("Content-Length", "" + (param.length + name.length()));
    conn.addRequestProperty("Content-Type", "multipart/mixed");

    try
    {
        conn.setRequestMethod("POST");
        conn.setUseCaches(false);
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setReadTimeout(15000);


        // Send request
        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
        wr.write(name.getBytes());
        wr.write(param);
        wr.flush();
        wr.close();
    }
    catch (ProtocolException e)
    {
        e.printStackTrace();
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }

    return;
}

我哪里错了?

4

1 回答 1

1

这是我使用的一段代码。

@POST
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response newFile(@FormDataParam("file") InputStream uploadInputStream, @FormDataParam("file") FormDataContentDisposition fileDetail, @FormDataParam("description") String description) {

    String uploadFileLocation = "C:/upload/documents/";

    OutputStream out = null;

    int read = 0;
    byte[] bytes = new byte[1024];

    File directory = new File(uploadFileLocation);
    if(!directory.exists()){
        directory.mkdirs();
    }
    out = new FileOutputStream(new File(directory, fileDetail.getFileName()));
    while ((read = uploadInputStream.read(bytes)) != -1) {
        out.write(bytes, 0, read);
    }

    out.flush();
    out.close();

//Return Response
...
}
于 2013-04-03T13:50:47.147 回答