无法使用jersey上传文件 [英] Unable to upload file with jersey

查看:78
本文介绍了无法使用jersey上传文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用此Web服务使用jersey上载文件

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

//保存它

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

当我执行代码时,出现405错误! 对这个问题有什么建议吗?

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

推荐答案

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

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

首先,您应该使用

public Response uploadPng(FormDataMultiPart multiPart) throws IOException {

接下来避免405错误添加

Next to avoid 405 error add

@Produces(MediaType.TEXT_PLAIN) 

uploadpng方法之上

above uploadpng method.

这篇关于无法使用jersey上传文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆