我正在使用Jersey开发一个休息服务器。我需要创建一个API,将图像上传到服务器上的文件夹中。我的API必须包含2个参数。字符串参数和File参数。
@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;
}
我哪里错了?
答案 0 :(得分: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
...
}