java – Http 415 on file上传使用jersey

前端之家收集整理的这篇文章主要介绍了java – Http 415 on file上传使用jersey前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我的RESTful文件上传代码
@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 – 表示part=@file.txt网址

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

解决方法

在尝试了很多例子后,最终在 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)

猜你在找的Java相关文章