将InputStream作为参数传递给Web服务

时间:2013-05-10 15:57:51

标签: java file-upload jersey

我正在尝试上传文件,但我没有通过html表单进行。不能使用QueryParam和PathParam。所以任何人都可以告诉如何传递流。

我的HttPClient看起来像:

try
    {
        HttpClient httpclient = new DefaultHttpClient();
        InputStream stream=new FileInputStream(new File("C:/localstore/ankita/Desert.jpg"));
        String url="http://localhost:8080/Cloud/webresources/fileupload";
        HttpPost httppost = new HttpPost(url);
        HttpResponse response = httpclient.execute(httppost);
    }
    catch(Exception e){}

我的Web服务类看起来有点像:

@Path("/fileupload")
public class UploadFileService {

@POST
@Consumes(MediaType.APPLICATION_OCTET_STREAM)

public Response uploadFile(InputStream in) throws IOException
{     
    String uploadedFileLocation = "c://filestore/Desert.jpg" ;

    // save it
    saveToFile(in, uploadedFileLocation);

    String output = "File uploaded via Jersey based RESTFul Webservice to: " + uploadedFileLocation;

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

}

// save uploaded file to new location
private 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();
    }

}

}

任何人都可以帮忙吗?

 String url="http://localhost:8080/Cloud/webresources/fileupload";
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);
        InputStreamEntity reqEntity = new InputStreamEntity(new FileInputStream(new File("C:/localstore/ankita/Desert.jpg")), -1);
        reqEntity.setContentType("binary/octet-stream");
        reqEntity.setChunked(true); // Send in multiple parts if needed
        httppost.setEntity(reqEntity);
        HttpResponse response = httpclient.execute(httppost);   

Web服务的外观如何?

1 个答案:

答案 0 :(得分:1)

你不能这样做。您无法在HTTP请求中传递流,因为流不可序列化。

执行此操作的方法是创建HttpEntity以包裹流(例如InputStreamEntity),然后使用HttpPOST将其附加到setEntity对象。然后发送POST,客户端将从您的流中读取并发送字节作为请求的“POST数据”。