Unable to upload file with jersey

倖福魔咒の 提交于 2019-12-11 08:46:45

问题


I am using this webservice to upload a file using 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;
    }

// save it

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

// save uploaded file to new location

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

When I execute my code i get a 405 error !! Are there any suggestions to this issue?


回答1:


public Response uploadPng(FormDataMultiPart multiPart) throws IOException {

You should pass the FormDataMultiPart parameter in the method which you are calling while uploading file.




回答2:


Not sure if this is perfect solution. But solved similar problem by following approach.

First thing, you should use

public Response uploadPng(FormDataMultiPart multiPart) throws IOException {

Next to avoid 405 error add

@Produces(MediaType.TEXT_PLAIN) 

above uploadpng method.



来源:https://stackoverflow.com/questions/23932436/unable-to-upload-file-with-jersey

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!