CXF 实现 REST 方式上传文件
/** * */ package com.demo.rest; import java.io.IOException; import java.io.InputStream; import java.util.Date; import javax.activation.DataHandler; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import org.apache.cxf.jaxrs.ext.multipart.Attachment; import org.apache.cxf.jaxrs.ext.multipart.ContentDisposition; import org.apache.cxf.jaxrs.ext.multipart.MultipartBody; import org.springframework.stereotype.Service; /** * @author michael * */ @Path("/image") @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) @Service public class ImageServiceResource { private static final String UPLOAD_FILE_NAME ="filename"; private static final String UPLOAD_FILE_TEMP ="tmp"; @POST @Path("/upload/{task}") @Consumes({ "multipart/form-data" }) public boolean attachImage(@PathParam("task") int task, MultipartBody body) { RestResult result = new RestResult(); try { addAttachment(body.getRootAttachment(),task); } catch (IOException e) { } catch (Exception e) { } return true; } @POST @Path("/uploads/{task}") @Consumes({ "multipart/form-data" }) public RestResult attachImages(@PathParam("task") int task, MultipartBody body) { RestResult result = new RestResult(); for (Attachment attachment : body.getAllAttachments()) { try { addAttachment(attachment,task); } catch (IOException e) { } catch (Exception e) { } } return true; } public void addAttachment(Attachment attachment, int task) throws Exception { try { DataHandler dataHandler = attachment.getDataHandler(); ContentDisposition cd =attachment.getContentDisposition(); String path = "c:/temp/"; String name = cd.getParameter(UPLOAD_FILE_NAME); if(name==null){ name =UPLOAD_FILE_TEMP+(new Date()).getTime()+"."+"jpg"; } UploadFileUtils.upload4Stream(name, path, dataHandler.getInputStream()); } catch (IOException e) { throw e; } catch (Exception e) { throw e; } } }