RESTful Web服务GET文件

时间:2011-05-05 11:00:12

标签: java rest jax-rs

我在java中实现了一个RESTful服务来上传文件。这是代码:

@POST
@Produces("text/plain")
public String uploadFile(@Context HttpServletRequest request) {

    String resultStatus = "fileupload error";
    String fileRepository = "/MobilityPatterns/";

    if (ServletFileUpload.isMultipartContent(request)) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(1073741824); //Limits the max file size (bytes)
        List<FileItem> items = null;
        try {
            items = upload.parseRequest(request);
        } catch (FileUploadException e) {
            e.printStackTrace();
        }

        String username = null;
        for(FileItem item : items){
            if(item.isFormField() && item.getFieldName().equalsIgnoreCase("username")){
                username = item.getString();
            } else if (!item.isFormField() && item.getSize() > 0) {
                try {
                    String filename = item.getName();

                    String dateFormat = "yyyyMMdd_HHmmss";
                    Calendar cal = Calendar.getInstance();
                    SimpleDateFormat dateFormatter = new SimpleDateFormat(dateFormat);
                    String date =  dateFormatter.format(cal.getTime());

                    item.write(new File(fileRepository + username + "_" + date + "_" + filename));
                    resultStatus = "fileupload success";
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
    return resultStatus;
}

但是现在我想实现一个服务来下载这个文件。我可以帮忙解决一下这个问题吗?

1 个答案:

答案 0 :(得分:0)

这样的事可能吗?我从来没有使用过jax-rs,所以我不确定我的代码是否会COMPUTE!

@GET
@Produces("application/x-octet-stream")
public void downloadFile(@Context HttpServletRequest request,@Context HttpServletResponse response) {
    //fetch the file id from request object
    //get File using file id
    //dump file contents to response
}