使用球衣上传文件上的 Http 415

2022-01-21 00:00:00 file-upload java jsp jersey

我的 RESTful 文件上传代码:

My code for RESTful file upload :

@Path("/upload") 
@POST 
@Consumes("multipart/form-data") 
public String post(
    @FormDataParam("part") String s, 
    @FormDataParam("part") FormDataContentDisposition d) { 
    return s + ":" + d.getFileName(); 
}

当我尝试使用 curl 上传文件时curl -X POST --form part=@file.txt url

When I try to upload a file using curl curl -X POST --form part=@file.txt url

我收到 HTTP 415-不支持的媒体类型错误.怎么了?

I am getting a HTTP 415-Unsupported Media Type Error. What is wrong ?

推荐答案

在尝试了很多示例之后,最终在 http://iambigd.blogspot.com/2011/06/java-upload-file-using-jersey.html

After trying a lot of examples finaly find the realy working example on http://iambigd.blogspot.com/2011/06/java-upload-file-using-jersey.html

@POST
@Path("/simpleupload")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public void simpleUpload(
    //@Context UriInfo ui,
    @Context HttpServletRequest request
){
    String fileRepository = "D:\";
    if (ServletFileUpload.isMultipartContent(request)) {
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    List<FileItem> items = null;
    try {
        items = upload.parseRequest(request);
    } catch (FileUploadException e) {
        e.printStackTrace();
    }
    if (items != null) {
        Iterator<FileItem> iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = iter.next();
            if (!item.isFormField() && item.getSize() > 0) {
            System.out.println("File is found.");
            String fileName = processFileName(item.getName());
            try {
                String savePath = fileRepository + fileName;
                System.out.println("savePath:" + savePath);
                item.write(new File(savePath));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else{
            System.out.println("getFieldName:" + item.getFieldName());
            System.out.println(item.getString());
        }
     }
   }
}
}

(需要servlet-api.jar、(apache)commons-oi.jar和(apache)commons-fileupload.jar)

(need the servlet-api.jar, (apache) commons-oi.jar and (apache) commons-fileupload.jar)

相关文章