本文整理汇总了Java中com.sun.jersey.multipart.FormDataMultiPart类的典型用法代码示例。如果您正苦于以下问题:Java FormDataMultiPart类的具体用法?Java FormDataMultiPart怎么用?Java FormDataMultiPart使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
FormDataMultiPart类属于com.sun.jersey.multipart包,在下文中一共展示了FormDataMultiPart类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: addFiles
import com.sun.jersey.multipart.FormDataMultiPart; //导入依赖的package包/类
@POST @Path("add/files")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public void addFiles(FormDataMultiPart body) {
List<IBridge.UploadedFileInfo> files = new LinkedList<>();
for(BodyPart part : body.getBodyParts()) {
InputStream is = part.getEntityAs(InputStream.class);
ContentDisposition meta = part.getContentDisposition();
try {
File tmpFile = File.createTempFile("dlup", ".dat");
tmpFile.deleteOnExit();
FileUtils.copyInputStreamToFile(is, tmpFile);
LOGGER.info("File {} uploaded to {}", meta.getFileName(), tmpFile);
files.add(new IBridge.UploadedFileInfo(tmpFile, meta.getFileName()));
} catch (IOException e) {
LOGGER.error("Cannot create temporary file for upload", e);
}
}
downloadsService.addFiles(files, globalConfig.getDownloadPath());
}
示例2: createRun
import com.sun.jersey.multipart.FormDataMultiPart; //导入依赖的package包/类
protected Run createRun(Sequence<Corpus> plan, HttpContext httpContext, MultivaluedMap<String,String> formParams, FormDataMultiPart formData, AlvisNLPExecutor executor, String... excludedParams) throws IOException {
Run result = new Run(rootProcessingDir, plan, executor);
if (formData != null) {
setFormParams(formData, result, excludedParams);
}
if (formParams != null) {
setMultivaluedMapParams(formParams, result, excludedParams);
}
if (httpContext != null) {
HttpRequestContext requestContext = httpContext.getRequest();
MultivaluedMap<String,String> params = requestContext.getQueryParameters();
setMultivaluedMapParams(params, result, excludedParams);
}
result.write();
return result;
}
示例3: serialize
import com.sun.jersey.multipart.FormDataMultiPart; //导入依赖的package包/类
/**
* Serialize the given Java object into string according the given
* Content-Type (only JSON is supported for now).
*/
public Object serialize(Object obj, String contentType, Map<String, Object> formParams) throws ApiException {
if (contentType.startsWith("multipart/form-data")) {
FormDataMultiPart mp = new FormDataMultiPart();
for (Entry<String, Object> param: formParams.entrySet()) {
if (param.getValue() instanceof File) {
File file = (File) param.getValue();
mp.bodyPart(new FileDataBodyPart(param.getKey(), file, MediaType.MULTIPART_FORM_DATA_TYPE));
} else {
mp.field(param.getKey(), parameterToString(param.getValue()), MediaType.MULTIPART_FORM_DATA_TYPE);
}
}
return mp;
} else if (contentType.startsWith("application/x-www-form-urlencoded")) {
return this.getXWWWFormUrlencodedParams(formParams);
} else {
// We let Jersey attempt to serialize the body
return obj;
}
}
示例4: upload
import com.sun.jersey.multipart.FormDataMultiPart; //导入依赖的package包/类
public void upload(String fileName, String sourceId,
String fileTypeId, InputStream inputStream)
throws ClientException {
String path = UriBuilder
.fromPath("/api/protected/file/upload/")
.segment(sourceId)
.segment(fileTypeId)
.build().toString();
FormDataMultiPart part = new FormDataMultiPart();
part.bodyPart(
new FormDataBodyPart(
FormDataContentDisposition
.name("file")
.fileName(fileName)
.build(),
inputStream, MediaType.APPLICATION_OCTET_STREAM_TYPE));
doPostMultipart(path, part);
}
示例5: doUploadFile
import com.sun.jersey.multipart.FormDataMultiPart; //导入依赖的package包/类
ClientResponse.Status doUploadFile(WebResource webResource, File file, String sourceId, String fileTypeId) throws ClientHandlerException, UniformInterfaceException, IOException {
try (InputStream is = new FileInputStream(file)) {
FormDataMultiPart part =
new FormDataMultiPart();
part.bodyPart(
new FormDataBodyPart(
FormDataContentDisposition
.name("file")
.fileName(file.getName())
.build(),
is, MediaType.APPLICATION_OCTET_STREAM_TYPE));
ClientResponse response = webResource
.path("/api/protected/file/upload/" + sourceId + "/" + fileTypeId)
.type(MediaType.MULTIPART_FORM_DATA_TYPE)
.post(ClientResponse.class, part);
ClientResponse.Status result = response.getClientResponseStatus();
return result;
}
}
示例6: annotate_POST_MULTIPART
import com.sun.jersey.multipart.FormDataMultiPart; //导入依赖的package包/类
@POST
@Path("/plans/{plan}/{sync:sync|async}")
@Consumes({ MediaType.MULTIPART_FORM_DATA })
public Response annotate_POST_MULTIPART(
@Context ServletContext servletContext,
@Context HttpContext httpContext,
@PathParam("plan") String planName,
@PathParam("sync") String sync,
@FormDataParam("text") @DefaultValue("") String text,
@FormDataParam("sourcedb") @DefaultValue("") String sourcedb,
@FormDataParam("sourceid") @DefaultValue("") String sourceid,
FormDataMultiPart formData
) throws Exception {
return annotate(servletContext, httpContext, planName, text, sourcedb, sourceid, null, formData, sync.equals("async"));
}
示例7: annotate
import com.sun.jersey.multipart.FormDataMultiPart; //导入依赖的package包/类
private Response annotate(
ServletContext servletContext,
HttpContext httpContext,
String planName,
String text,
String sourcedb,
String sourceid,
MultivaluedMap<String,String> formParams,
FormDataMultiPart formData,
boolean async
) throws Exception {
Sequence<Corpus> plan = planBuilder.buildPlan(planName);
AlvisNLPExecutor executor = getExecutor(servletContext);
Run run = createRun(plan, httpContext, formParams, formData, executor, "text", "sourcedb", "sourceid");
injectInputText(run, text, sourcedb, sourceid);
planBuilder.setParams(run, plan);
planBuilder.check(plan);
run.execute(servletContext, planBuilder, async);
if (async) {
return fetch(run.getId());
}
return createSyncRunResponse(run);
}
示例8: setFormParams
import com.sun.jersey.multipart.FormDataMultiPart; //导入依赖的package包/类
private static void setFormParams(FormDataMultiPart formData, Run run, String... excluded) throws IOException {
Collection<String> ex = new HashSet<String>(Arrays.asList(excluded));
Map<String,List<FormDataBodyPart>> formFields = formData.getFields();
for (Map.Entry<String,List<FormDataBodyPart>> e : formFields.entrySet()) {
String name = e.getKey();
if (ex.contains(name)) {
continue;
}
List<FormDataBodyPart> fields = e.getValue();
if (fields.isEmpty()) {
continue;
}
FormDataBodyPart field = fields.get(fields.size() - 1);
if (name.startsWith(ParamValue.METHOD_UPLOAD + "-")) {
name = name.substring(7);
ContentDisposition cd = field.getContentDisposition();
run.addUploadParamValue(name, cd.getFileName(), field.getValueAs(InputStream.class));
}
else {
String value = field.getValue();
setParam(run, name, value);
}
}
}
示例9: serialize
import com.sun.jersey.multipart.FormDataMultiPart; //导入依赖的package包/类
/**
* Serialize the given Java object into string according the given
* Content-Type (only JSON is supported for now).
*/
public Object serialize(Object obj, String contentType, Map<String, Object> formParams) throws ApiException {
if (contentType.startsWith("multipart/form-data")) {
FormDataMultiPart mp = new FormDataMultiPart();
for (Entry<String, Object> param : formParams.entrySet()) {
if (param.getValue() instanceof File) {
File file = (File) param.getValue();
mp.bodyPart(new FileDataBodyPart(param.getKey(), file, MediaType.MULTIPART_FORM_DATA_TYPE));
} else {
mp.field(param.getKey(), parameterToString(param.getValue()), MediaType.MULTIPART_FORM_DATA_TYPE);
}
}
return mp;
} else if (contentType.startsWith("application/x-www-form-urlencoded")) {
return this.getXWWWFormUrlencodedParams(formParams);
} else {
// We let Jersey attempt to serialize the body
return obj;
}
}
示例10: saveSpecificFile
import com.sun.jersey.multipart.FormDataMultiPart; //导入依赖的package包/类
/**
* save file to folder on server
* @param centralConfigService - central config service
* @param formDataMultiPart - multi part - file content
* @param uploadDir - upload dir
* @param fileName - file name
*/
public static void saveSpecificFile(CentralConfigService centralConfigService,
FormDataMultiPart formDataMultiPart, String uploadDir, String fileName) {
int fileUploadMaxSizeMb = centralConfigService.getMutableDescriptor().getFileUploadMaxSizeMb();
// get uploaded file map
Map<String, List<FormDataBodyPart>> fields = formDataMultiPart.getFields();
fields.forEach((name, dataBody) -> {
List<FormDataBodyPart> formDataBodyParts = fields.get(name);
// get file name and data
byte[] fileAsBytes = formDataBodyParts.get(0).getValueAs(byte[].class);
if (FileUtils.bytesToMeg(fileAsBytes.length) > fileUploadMaxSizeMb && fileUploadMaxSizeMb > 0) {
throw new BadRequestException("Uploaded file size is bigger than :" + fileUploadMaxSizeMb);
}
String fileLocation = uploadDir + File.separator + fileName;
FileUtils.writeFile(fileLocation, fileAsBytes);
});
}
示例11: upload
import com.sun.jersey.multipart.FormDataMultiPart; //导入依赖的package包/类
public ClientResponse<File> upload(String url, File f, Headers... headers) {
@SuppressWarnings("resource")
FormDataMultiPart form = new FormDataMultiPart();
form.bodyPart(new FileDataBodyPart("file", f, MediaType.APPLICATION_OCTET_STREAM_TYPE));
String urlCreated = createURI(url);
ClientConfig cc = new DefaultClientConfig();
cc.getClasses().add(MultiPartWriter.class);
WebResource webResource = Client.create(cc).resource(urlCreated);
Builder builder = webResource.type(MULTIPART_MEDIA).accept(MEDIA).accept("text/plain");
for (Headers h : headers) {
builder.header(h.getKey(), h.getValue());
}
com.sun.jersey.api.client.ClientResponse clienteResponse = null;
clienteResponse = builder.post(com.sun.jersey.api.client.ClientResponse.class, form);
return new ClientResponse<File>(clienteResponse, File.class);
}
示例12: upload
import com.sun.jersey.multipart.FormDataMultiPart; //导入依赖的package包/类
/**
* upload from the given inputstream
*
* @param fileToUpload
* @param filename
* @param contents
* @param comment
* @throws Exception
*/
public synchronized void upload(InputStream fileToUpload, String filename,
String contents, String comment) throws Exception {
TokenResult token = getEditToken("File:" + filename, "edit");
final FormDataMultiPart multiPart = new FormDataMultiPart();
// http://stackoverflow.com/questions/5772225/trying-to-upload-a-file-to-a-jax-rs-jersey-server
multiPart.bodyPart(new StreamDataBodyPart("file", fileToUpload));
multiPart.field("filename", filename);
multiPart.field("ignorewarnings", "true");
multiPart.field("text", contents);
if (!comment.isEmpty())
multiPart.field("comment", comment);
String params = "";
Api api = this.getActionResult("upload", params, token, multiPart);
handleError(api);
}
示例13: saveFileToTempFolder
import com.sun.jersey.multipart.FormDataMultiPart; //导入依赖的package包/类
/**
* upload file to temp folder
*
* @param artifactoryRequest - encapsulate data related to request
* @param response - encapsulate data require for response
* @return - true if uploaded successful
*/
private List<String> saveFileToTempFolder(ArtifactoryRestRequest artifactoryRequest, RestResponse response) {
String uploadDir = ContextHelper.get().getArtifactoryHome().getTempUploadDir().getAbsolutePath();
List<String> fileNames = new ArrayList<>();
try {
MultiPartUtils.createTempFolderIfNotExist(uploadDir);
// get upload model
UploadArtifactInfo uploadArtifactInfo = (UploadArtifactInfo) artifactoryRequest.getImodel();
// save file data tto temp
FormDataMultiPart formDataMultiPart = uploadArtifactInfo.fetchFormDataMultiPart();
String fileName = formDataMultiPart.getFields().get("file").get(0).getContentDisposition().getFileName();
MultiPartUtils.saveFileDataToTemp(centralConfigService, formDataMultiPart, uploadDir,
fileNames, true);
fileNames.add(fileName);
} catch (Exception e) {
response.error(e.getMessage());
}
return fileNames;
}
示例14: sendComplexMessage
import com.sun.jersey.multipart.FormDataMultiPart; //导入依赖的package包/类
private ClientResponse sendComplexMessage(String recipient) {
Client client = Client.create();
client.addFilter(new HTTPBasicAuthFilter("api", MAILGUN_API_KEY));
FormDataMultiPart formData = new FormDataMultiPart();
formData.field("from", "Mailgun User <[email protected]" + MAILGUN_DOMAIN_NAME + ">");
formData.field("to", recipient);
formData.field("subject", "Complex Mailgun Example");
formData.field("html", "<html>HTML <strong>content</strong></html>");
ClassLoader classLoader = getClass().getClassLoader();
File txtFile = new File(classLoader.getResource("example-attachment.txt").getFile());
formData.bodyPart(new FileDataBodyPart("attachment", txtFile, MediaType.TEXT_PLAIN_TYPE));
WebResource webResource = client.resource(
"https://api.mailgun.net/v3/" + MAILGUN_DOMAIN_NAME + "/messages");
return webResource.type(MediaType.MULTIPART_FORM_DATA_TYPE)
.post(ClientResponse.class, formData);
}
示例15: uploadTestImage
import com.sun.jersey.multipart.FormDataMultiPart; //导入依赖的package包/类
static private String uploadTestImage() {
TwitterAdsClient.setTrace(false);
TwitterAdsClient.setSandbox(true);
// upload image
String domain = "https://upload.twitter.com";
String resource = "/1.1/media/upload.json";
String filePath = "src/test/resources/angry.bird.800.320.png";
ClientService clientService = ClientServiceFactory.getInstance();
Client client = clientService.getClient();
WebResource webResource = client.resource(domain);
final FileDataBodyPart filePart = new FileDataBodyPart("media", new File(filePath));
final FormDataMultiPart formDataMultiPart = new FormDataMultiPart();
FormDataMultiPart multiPart = (FormDataMultiPart) formDataMultiPart.bodyPart(filePart);
ClientResponse response = webResource.path(resource).type(MediaType.MULTIPART_FORM_DATA_TYPE)
.accept(MediaType.APPLICATION_JSON_TYPE).post(ClientResponse.class, multiPart);
if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
}
String output = response.getEntity(String.class);
JsonObject jsonObj = new JsonParser().parse(output).getAsJsonObject();
return jsonObj.get("media_id_string").getAsString();
}