如何使用Jersey上传文件

时间:2016-11-02 14:42:36

标签: java jersey jetty

我正在尝试为上传文件创建服务。

我按照指南https://examples.javacodegeeks.com/enterprise-java/rest/jersey/jersey-file-upload-example/

但是当我想要跑步时我得到了

Status Code:405 Method Not Allowed

我做错了什么?

这是我的代码

服务器

@Path("/doc")
public class DocResource extends BaseResource<DocDao, DocEntity>
{
    @POST
    @Path("/uploadDoc")
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    public String uploadFile(@Context HttpServletRequest req,
            @FormDataParam("file") InputStream fileInputStream,
            @FormDataParam("file") FormDataContentDisposition contentDispositionHeader) {

        String filePath = SERVER_UPLOAD_LOCATION_FOLDER + contentDispositionHeader.getFileName();

        // save the file to the server
        saveFile(fileInputStream, filePath);

        String output = "File saved to server location : " + filePath;

        return output;

    }

    // save uploaded file to a defined location on the server
    private void saveFile(InputStream uploadedInputStream,
            String serverLocation) {

        try {
            OutputStream outpuStream = new FileOutputStream(new File(serverLocation));
            int read = 0;
            byte[] bytes = new byte[1024];

            outpuStream = new FileOutputStream(new File(serverLocation));
            while ((read = uploadedInputStream.read(bytes)) != -1) {
                outpuStream.write(bytes, 0, read);
            }
            outpuStream.flush();
            outpuStream.close();
        } catch (IOException e) {

            e.printStackTrace();
        }

    }

}

HTML

<div class="modal fade" id="addEditDoc" tabindex="-1" role="dialog" aria-labelledby="addEditDoc" data-backdrop="false" data-keyboard="false">    
    <div class="modal-dialog addEditDocModal" role="document">
        <div class="modal-content myModal">    
            <h1>Upload a File</h1>

                <form action="http://127.0.0.1:8080/maintenance/uploadDoc" method="GET" enctype="multipart/form-data">

                   <p>
                        Select a file : <input type="file" name="file" size="50" />
                   </p>

                   <input type="submit" value="Upload It" />
                </form>
        </div>
    </div>    
</

1 个答案:

答案 0 :(得分:1)

我认为该方法必须是POST而不是GET

请查看更多文档Here

 <div class="modal-dialog addEditDocModal" role="document">
        <div class="modal-content myModal">    
            <h1>Upload a File</h1>

                <form action="http://127.0.0.1:8080/maintenance/doc/uploadDoc" method="POST" enctype="multipart/form-data">

                   <p>
                        Select a file : <input type="file" name="file" size="50" />
                   </p>

                   <input type="submit" value="Upload It" />
                </form>
        </div>
    </div>