2017-12-26 34 views
0

ジャージーファイルのアップロードサービスを作成する際に問題が発生しています。ジャージー:マルチパートフォームファイルのアップロードサポートされていないメディアタイプ(415)

この仕様は次のとおりです。サーバーは、クライアントがGETメソッドを使用してファイルにアクセスすることを許可します。 index.htmlを使用すると、マルチパート・フォーム・データ・ハンドラーを使用して複数のファイルをPOSTにすることができます。

しかし、CSVファイル(Content-Type: text/csv)をアップロードしようとすると、サーバは直ちに415エラーで応答し、ハンドラメソッドコードを入力したり、エラーを吐き出したりしません。あなたの助けを事前に

@Path("/ui/") 
public class HtmlServer { 
    static final Logger LOGGER = Logger.getLogger(HtmlServer.class.getCanonicalName()); 

    @GET 
    @Path("/{file}") 
    @Produces(MediaType.TEXT_HTML) 
    public Response request(@PathParam("file") @DefaultValue("index.html") String path) { 
     LOGGER.info("HTTP GET /ui/" + path); 

     String data; 
     try { 
      if ("".equals(path)) 
       data = getFileBytes("web/index.html"); 
      else 
       data = getFileBytes("web/" + path); 
      return Response.ok(data, MediaType.TEXT_HTML).build(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
      return Response.ok("<h1>Server error</h1>", MediaType.TEXT_HTML).build(); 
     } 
    } 

    @POST 
    @Path("/{file}") 
    @Consumes(MediaType.MULTIPART_FORM_DATA) 
    public Response uploadFiles(final FormDataMultiPart multiPart) { 
     List<FormDataBodyPart> bodyParts = multiPart.getFields("dataset"); 

     StringBuffer fileDetails = new StringBuffer(""); 

     /* Save multiple files */ 
     for (int i = 0; i < bodyParts.size(); i++) { 
      BodyPartEntity bodyPartEntity = (BodyPartEntity) bodyParts.get(i).getEntity(); 
      String fileName = bodyParts.get(i).getContentDisposition().getFileName(); 
      saveToFile(bodyPartEntity.getInputStream(), "/.../" + fileName); 
      fileDetails.append(" File saved to /.../" + fileName); 
     } 

     System.out.println(fileDetails); 

     return Response.ok(fileDetails.toString()).build(); 
    } 

    private static String getFileBytes(String path) throws IOException { 
     byte[] bytes = Files.toByteArray(new File(path)); 
     return new String(bytes); 
    } 

    private static 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(); 
     } 
    } 
} 

ありがとう:

は、ここに私のコードです!

答えて

0

multipart/form-dataを受け入れるようにエンドポイントを設定していますが、のアップロード中にtext/csvと設定されているというのが問題だと思います。要求のcontent-typemultipart/form-dataと設定する必要があります。

APIをテストするためにPOSTMANを使用している場合は、テキストまたはファイルを渡すことができるform-dataというオプションがあります。他のRESTクライアントにも同様のオプションがあるか、コンテンツタイプを手動で設定する必要があります。

+0

私は 'enctype =" multipart/form-data "を使って死んだ単純なhtml形式でAPIをテストしています –

関連する問題