使用jersey上传Http 415

我的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 –form part=@file.txt url上传文件时

我收到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)

以上是 使用jersey上传Http 415 的全部内容, 来源链接: utcz.com/qa/412768.html

回到顶部