【问题标题】:Error in uploading a file using Jersey rest service使用 Jersey rest 服务上传文件时出错
【发布时间】:2014-07-22 16:30:48
【问题描述】:

我正在使用 jersey 构建将上传文件的休息服务。但是我在将文件写入所需位置时遇到了问题。 Java 抛出系统找不到指定路径错误。这是我的网络服务:

@POST
    @Path("/fileupload")
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    public Response uploadFile(@FormDataParam("file")InputStream fileUploadStream, @FormDataParam("file")FormDataContentDisposition fileDetails) throws IOException{

        StringBuilder uploadFileLocation= new StringBuilder();

          uploadFileLocation.append("c:/logparser/webfrontend/uploads");
        uploadFileLocation.append("/"+dateFormat.format(Calendar.getInstance().getTime()));
        uploadFileLocation.append("/"+fileDetails.getFileName());
        writeToFile(fileUploadStream, uploadFileLocation.toString());
        return Response.status(200).entity("File saved to " + uploadFileLocation).build();
    }

    private void writeToFile(InputStream uploadInputStream, String uploadFileLocation)
    {
        log.debug("UploadService , writeToFile method , start ()");

        try{
            int read = 0;
            byte[] bytes = new byte[uploadInputStream.available()];

            log.info("UploadService, writeToFile method , copying uploaded files.");
        OutputStream out = new FileOutputStream(new File(uploadFileLocation));
            while ((read = uploadInputStream.read(bytes)) != -1)
            {
                out.write(bytes, 0, read);
            }
            out.flush();
            out.close();
        }
        catch(Exception e)
        {
            log.error("UploadService, writeToFile method, error in writing to file "+e.getMessage());
        }
    }

【问题讨论】:

    标签: rest file-upload jersey multipartform-data


    【解决方案1】:

    仅查看代码(包含异常和堆栈跟踪通常很有帮助),您正在尝试根据尚不存在的时间戳写入目录。尝试添加对 File.mkdir/mkdirs 的调用。请参阅此问题/答案:FileNotFoundException (The system cannot find the path specified)

    旁注 - 除非你有理由不这样做,否则我会考虑使用 Apache commons-io(FileUtils.copyInputStreamToFile) 之类的东西来编写。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-17
      • 1970-01-01
      • 2018-08-02
      • 2015-06-01
      • 2014-03-16
      • 2014-07-31
      相关资源
      最近更新 更多