使用" multipart / form-data"严重错误用于文件上传服务 - Apache Jersey

时间:2011-12-28 16:06:13

标签: java rest jersey

我收到此错误:

SEVERE: Resource methods utilizing @FormParam and consuming "multipart/form-data" are no longer supported. See @FormDataParam

当我为基于Apache Jersey的Rest Web服务完成客户端Web访问时,我现在正在工作:

@POST
@Path("upload")
@Consumes("multipart/form-data")
@Produces("text/plain")
public String uploadFile(@FormParam("file") File file, @FormParam("file") FormDataContentDisposition fileDetail) {
    String fileLocation = "/files/" + fileDetail.getFileName();
    System.out.println("File location: " + fileLocation);
    // Load image
    try {
        byte[] imageBytes = loadImage(fileLocation);
        MongoConnection conn = MongoUtil.getConnection();
        conn.connect("m1", "avatar"); 
        GridFS fs = new GridFS(conn.getDB());
        GridFSInputFile in = fs.createFile(imageBytes);
        in.save();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return "1";
}

我尝试从@FormParam更改为@FormDataParam,但尚未解决。

有什么可以解决这个问题?

2 个答案:

答案 0 :(得分:2)

试试这个:

@Path("upload")
@Consumes("multipart/form-data")
@POST
public void handleUpload(@FormParam("file") InputStream file) throws Exception {
// do your thing
}

您也可以参考this post

对于客户端:

import java.io.File;

import javax.ws.rs.core.MediaType;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.multipart.FormDataMultiPart;

public class UploadExample {
  public void upload(String url, File f, String formName) {
    FormDataMultiPart form = new FormDataMultiPart().field(formName, f, MediaType.MULTIPART_FORM_DATA_TYPE);
    WebResource webResource = Client.create().resource(url);
    webResource.type(MediaType.MULTIPART_FORM_DATA)
               .accept(MediaType.TEXT_PLAIN)
               .post(form);
    }
}

答案 1 :(得分:1)

您必须下载并使用jersey-multipart.jar