无法使用泽西上传文件

时间:2014-05-29 11:37:53

标签: java rest upload jersey

我正在使用此网络服务使用泽西上传文件

public class upload {
@POST
@Path(value = "upload")
@Consumes("image/jpg")
public Response uploadPng(File file) throws IOException {
    file = new File("C:/Users/Marwa/Desktop/Capture.jpg");
    String uploadedFileLocation = "C:/Users/Desktop/" + file.getName();
    DataInputStream diStream =new DataInputStream(new FileInputStream(file));
    long len = (int) file.length();
    byte[] fileBytes = new byte[(int) len];
    int read = 0;
    int numRead = 0;
    while (read < fileBytes.length && (numRead =diStream.read(fileBytes, read,fileBytes.length - read)) >= 0) {
        read = read + numRead;
    }

//保存

    writeToFile(diStream, uploadedFileLocation);
    System.out.println("File uploaded to : " + uploadedFileLocation);
    return Response.status(200).entity(file).build();
  }

//将上传的文件保存到新位置

private void writeToFile(InputStream uploadedInputStream,String uploadedFileLocation) {
    try {
        OutputStream out =new FileOutputStream(new File(uploadedFileLocation));
        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();}}}

当我执行我的代码时,我得到405错误! 对这个问题有任何建议吗?

2 个答案:

答案 0 :(得分:0)

public Response uploadPng(FormDataMultiPart multiPart) throws IOException {

在上传文件时,您应该在调用的方法中传递FormDataMultiPart参数。

答案 1 :(得分:0)

不确定这是否是完美的解决方案。但是通过以下方法解决了类似的问题。

首先,您应该使用

public Response uploadPng(FormDataMultiPart multiPart) throws IOException {

接下来避免405错误添加

@Produces(MediaType.TEXT_PLAIN) 

上面的uploadpng方法。