jersey文件上传

最近在搞webService的文件上传。服务器端好搞,就是客户端比较麻烦,mark一下。

服务端的代码:

@POST
@Path("uploadFile")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_XML)
public String uploadFile(FormDataMultiPart form) {
    String filePath;
    String baseUrl = AppConfig.getProperty("res.root.path");
    try {
        UploadRule rule = new UploadRule(baseUrl,Constants.SPT + UploadRule.ACCESS_SCOPE_PROTECTED + SCOPE);
        //boay中可能有多个附件,循环出来
        List v1 = form.getBodyParts();
        List paths = new ArrayList();
        for (BodyPart p : v1) {
            FormDataBodyPart vPart = (FormDataBodyPart) p;
            InputStream v = vPart.getValueAs(InputStream.class);
            String fileName = vPart.getName();
            File destDir = new File("d:/upload/files");
            if(!destDir.exists()) 
                destDir.mkdirs(); 
            OutputStream outputStream = new FileOutputStream(new File("d:/upload/files/"+fileName ));
            int length = 0;
            byte[] buff = new byte[1024];
            while (-1 != (length = v.read(buff))) {
                outputStream.write(buff, 0, length);
            }
            v.close();
            outputStream.close();
            filePath = "d:/upload/files/"+fileName 
        }
        response.setPaths(paths);
        return filePath;
    } catch (Exception e) {
        e.printStackTrace();
        response.setResponseStatus(BaseResponse.RESPONSE_STATUS_ERROR);
        response.setResponseMessage(BaseUtil.getStackTrace(e));
        return filePath;  
 }
}
 客户端代码: 
  

public static void main(String[] args) {
		ClientConfig config = new DefaultClientConfig();
		Client client = Client.create(config);
		//上传的地址
		WebResource r = client.resource("http://jjy.cost168.com/api/upload/uploadFile");
		FormDataMultiPart form=new FormDataMultiPart();
			File f = new File("d:/x1.txt");
			InputStream file = null;
			try {
				file = new FileInputStream(f);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
			FormDataBodyPart formDataBodyPart = new FormDataBodyPart();
			//这里指定上传时的类型
			formDataBodyPart.setValue(MediaType.MULTIPART_FORM_DATA_TYPE, file);
			formDataBodyPart.setName("x1.txt");
			form.getBodyParts().add(formDataBodyPart);//这样写的好处是可以上传多个附件
			//这里的type也要指定为data
			FilesResponse files = r.accept(MediaType.APPLICATION_XML).type(MediaType.MULTIPART_FORM_DATA).post(FilesResponse.class, form);
			for (String string : files.getPaths()) {
				System.out.println(string);
			}
	}
需要用到的jar


	com.cost168.lib.bl
	rest_core
	0.0.1-SNAPSHOT


	com.sun.jersey
	jersey-core
	1.17.1


	com.sun.jersey
	jersey-client
	1.17.1


	com.sun.jersey
	jersey-json
	1.17.1


	com.sun.jersey.contribs
	jersey-multipart
	1.17.1













你可能感兴趣的:(Java,jersey)