我的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)