http://www.programcreek.com/java-api-examples/index.php?api=javax.servlet.http.Part

The following are 20 Jave code examples that show how to use the javax.servlet.http.Part class. These examples are extracted from open source projects. You can click  to vote up the examples you like. Your votes will be used in an intelligent system to get more and better code examples. Thanks!

Example 1

  8 

From project spring-framework, under directory /spring-web/src/main/java/org/springframework/web/multipart/support/, in source file StandardMultipartHttpServletRequest.java

public String getMultipartContentType(String paramOrFileName){
try {
Part part=getPart(paramOrFileName);
return (part != null ? part.getContentType() : null);
}
catch ( Exception ex) {
throw new MultipartException("Could not access multipart servlet request",ex);
}
}

Example 2

  8 

From project spring-framework, under directory /spring-web/src/main/java/org/springframework/web/multipart/support/, in source file StandardMultipartHttpServletRequest.java

public HttpHeaders getMultipartHeaders(String paramOrFileName){
try {
Part part=getPart(paramOrFileName);
if (part != null) {
HttpHeaders headers=new HttpHeaders();
for ( String headerName : part.getHeaderNames()) {
headers.put(headerName,new ArrayList<String>(part.getHeaders(headerName)));
}
return headers;
}
else {
return null;
}
}
catch ( Exception ex) {
throw new MultipartException("Could not access multipart servlet request",ex);
}
}

Example 3

  7 

From project ohmageServer, under directory /src/org/ohmage/request/, in source file Request.java

/**
* Reads the HttpServletRequest for a key-value pair and returns the value where the key is equal to the given key.
* @param httpRequest A "multipart/form-data" request that contains the parameter that has a key value 'key'.
* @param key The key for the value we are after in the 'httpRequest'.
* @return Returns null if there is no such key in the request or if, after reading the object, it has a length of 0. Otherwise, it returns the value associated with the key as a byte array.
* @throws ServletException Thrown if the 'httpRequest' is not a "multipart/form-data" request.
* @throws IOException Thrown if there is an error reading the value fromthe request's input stream.
* @throws IllegalStateException Thrown if the entire request is largerthan the maximum allowed size for a request or if the value of the requested key is larger than the maximum allowed size for a single value.
*/
protected byte[] getMultipartValue(HttpServletRequest httpRequest,String key) throws ValidationException {
try {
Part part=httpRequest.getPart(key);
if (part == null) {
return null;
}
InputStream partInputStream=part.getInputStream();
ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
byte[] chunk=new byte[4096];
int amountRead;
while ((amountRead=partInputStream.read(chunk)) != -1) {
outputStream.write(chunk,0,amountRead);
}
if (outputStream.size() == 0) {
return null;
}
else {
return outputStream.toByteArray();
}
}
catch ( ServletException e) {
LOGGER.error("This is not a multipart/form-data POST.",e);
setFailed(ErrorCode.SYSTEM_GENERAL_ERROR,"This is not a multipart/form-data POST which is what we expect for the current API call.");
throw new ValidationException(e);
}
catch ( IOException e) {
LOGGER.error("There was an error reading the message from the input stream.",e);
setFailed();
throw new ValidationException(e);
}
}

Example 4

  7 

From project Ohmage_Server_2, under directory /src/org/ohmage/request/, in source file Request.java

/**
* Reads the HttpServletRequest for a key-value pair and returns the value where the key is equal to the given key.
* @param httpRequest A "multipart/form-data" request that contains the parameter that has a key value 'key'.
* @param key The key for the value we are after in the 'httpRequest'.
* @return Returns null if there is no such key in the request or if, after reading the object, it has a length of 0. Otherwise, it returns the value associated with the key as a byte array.
* @throws ServletException Thrown if the 'httpRequest' is not a "multipart/form-data" request.
* @throws IOException Thrown if there is an error reading the value fromthe request's input stream.
* @throws IllegalStateException Thrown if the entire request is largerthan the maximum allowed size for a request or if the value of the requested key is larger than the maximum allowed size for a single value.
*/
protected byte[] getMultipartValue(HttpServletRequest httpRequest,String key) throws ValidationException {
try {
Part part=httpRequest.getPart(key);
if (part == null) {
return null;
}
InputStream partInputStream=part.getInputStream();
ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
byte[] chunk=new byte[4096];
int amountRead;
while ((amountRead=partInputStream.read(chunk)) != -1) {
outputStream.write(chunk,0,amountRead);
}
if (outputStream.size() == 0) {
return null;
}
else {
return outputStream.toByteArray();
}
}
catch ( ServletException e) {
LOGGER.error("This is not a multipart/form-data POST.",e);
setFailed(ErrorCodes.SYSTEM_GENERAL_ERROR,"This is not a multipart/form-data POST which is what we expect for the current API call.");
throw new ValidationException(e);
}
catch ( IOException e) {
LOGGER.error("There was an error reading the message from the input stream.",e);
setFailed();
throw new ValidationException(e);
}
}

Example 5

  6 

From project Coffee-Framework, under directory /coffeeframework-core/src/main/java/coffee/, in source fileCoffeeRequestContext.java

/**
* @param part
* @return
*/
public String getParameterFilename(Part part){
for ( String cd : part.getHeader("content-disposition").split(";")) {
if (cd.trim().startsWith("filename")) {
String fileName=cd.substring(cd.indexOf('=') + 1).trim().replace("\"","");
fileName=fileName.substring(fileName.lastIndexOf('/') + 1).substring(fileName.lastIndexOf('\\') + 1);
return fileName;
}
}
return null;
}

Example 6

  5 

From project capedwarf-blue, under directory /blobstore/src/main/java/org/jboss/capedwarf/blobstore/, in source fileJBossBlobstoreService.java

public void storeUploadedBlobs(HttpServletRequest request) throws IOException, ServletException {
Map<String,BlobKey> map=new HashMap<String,BlobKey>();
Map<String,List<BlobKey>> map2=new HashMap<String,List<BlobKey>>();
for ( Part part : request.getParts()) {
if (ServletUtils.isFile(part)) {
BlobKey blobKey=storeUploadedBlob(part);
String name=part.getName();
map.put(name,blobKey);
List<BlobKey> list=map2.get(name);
if (list == null) {
list=new LinkedList<BlobKey>();
map2.put(name,list);
}
list.add(blobKey);
}
}
request.setAttribute(UPLOADED_BLOBKEY_ATTR,map);
request.setAttribute(UPLOADED_BLOBKEY_LIST_ATTR,map2);
}

Example 7

  5 

From project capedwarf-blue, under directory /blobstore/src/main/java/org/jboss/capedwarf/blobstore/, in source fileJBossBlobstoreService.java

private BlobKey storeUploadedBlob(Part part) throws IOException {
JBossFileService fileService=getFileService();
AppEngineFile file=fileService.createNewBlobFile(part.getContentType(),ServletUtils.getFileName(part));
ReadableByteChannel in=Channels.newChannel(part.getInputStream());
try {
FileWriteChannel out=fileService.openWriteChannel(file,true);
try {
IOUtils.copy(in,out);
}
finally {
out.closeFinally();
}
}
finally {
in.close();
}
return fileService.getBlobKey(file);
}

Example 8

  5 

From project capedwarf-blue, under directory /common/src/main/java/org/jboss/capedwarf/common/servlet/, in source fileServletUtils.java

public static String getFileName(Part part){
String contentDisposition=part.getHeader("content-disposition");
for ( String token : contentDisposition.split(";")) {
if (token.trim().startsWith("filename")) {
return token.substring(token.indexOf('=') + 1).trim().replace("\"","");
}
}
return null;
}

Example 9

  5 

From project Coffee-Framework, under directory /coffeeframework-core/src/main/java/coffee/, in source fileCoffeeRequestContext.java

/**
* @throws ServletException
* @throws IOException
* @throws FileUploadException
*/
public void parseMultiPartRequest() throws ServletException, IOException {
params=new HashMap<String,Object>();
for ( Part part : request.getParts()) {
String filename=getParameterFilename(part);
String fieldname=part.getName();
if (filename == null) {
String fieldvalue=getValue(part);
params.put(fieldname,fieldvalue);
}
else if (!filename.isEmpty()) {
if (reachedMaxFileSize(part)) throw new IOException("MAX_FILE_SIZE_REACHED");
params.put(fieldname,part);
}
}
}

Example 10

  5 

From project Coffee-Framework, under directory /coffeeframework-core/src/main/java/coffee/, in source fileCoffeeRequestContext.java

/**
* @param part
* @return
* @throws IOException
*/
public String getValue(Part part) throws IOException {
BufferedReader reader=new BufferedReader(new InputStreamReader(part.getInputStream(),"UTF-8"));
StringBuilder value=new StringBuilder();
char[] buffer=new char[1024];
for (int length=0; (length=reader.read(buffer)) > 0; ) {
value.append(buffer,0,length);
}
return value.toString();
}

Example 11

  5 

From project Coffee-Framework, under directory /coffeeframework-core/src/main/java/coffee/servlet/, in source fileJsonUploadServlet.java

public void doUpload(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {
Collection<Part> parts=request.getParts();
ArrayList<E> createdObjects=new ArrayList<E>();
for ( Part part : parts) {
String fileName=getFileName(part);
writeFile(part,fileName);
try {
createdObjects.add(saveFile(fileName,part));
}
catch ( Exception e) {
throw new ServletException("Can't save the file.",e);
}
}
PrintWriter writer=response.getWriter();
writer.write(new Gson().toJson(createdObjects));
}

Example 12

  5 

From project fileUploadServlet3JSF2, under directory /src/main/java/net/balusc/http/multipart/, in source fileMultipartMap.java

/**
* Global constructor.
*/
private MultipartMap(HttpServletRequest multipartRequest,String location,boolean multipartConfigured) throws ServletException, IOException {
multipartRequest.setAttribute(ATTRIBUTE_NAME,this);
this.encoding=multipartRequest.getCharacterEncoding();
if (this.encoding == null) {
multipartRequest.setCharacterEncoding(this.encoding=DEFAULT_ENCODING);
}
this.location=location;
this.multipartConfigured=multipartConfigured;
for ( Part part : multipartRequest.getParts()) {
String filename=getFilename(part);
if (filename == null) {
processTextPart(part);
}
else if (!filename.isEmpty()) {
processFilePart(part,filename);
}
}
}

Example 13

  5 

From project fileUploadServlet3JSF2, under directory /src/main/java/net/balusc/http/multipart/, in source fileMultipartMap.java

/**
* Returns the filename from the content-disposition header of the given part.
*/
private String getFilename(Part part){
for ( String cd : part.getHeader(CONTENT_DISPOSITION).split(";")) {
if (cd.trim().startsWith(CONTENT_DISPOSITION_FILENAME)) {
return cd.substring(cd.indexOf('=') + 1).trim().replace("\"","");
}
}
return null;
}

Example 14

  5 

From project fileUploadServlet3JSF2, under directory /src/main/java/net/balusc/http/multipart/, in source fileMultipartMap.java

/**
* Process given part as Text part.
*/
private void processTextPart(Part part) throws IOException {
String name=part.getName();
String[] values=(String[])super.get(name);
if (values == null) {
put(name,new String[]{getValue(part)});
}
else {
int length=values.length;
String[] newValues=new String[length + 1];
System.arraycopy(values,0,newValues,0,length);
newValues[length]=getValue(part);
put(name,newValues);
}
}

Example 15

  5 

From project fileUploadServlet3JSF2, under directory /src/main/java/net/balusc/http/multipart/, in source fileMultipartMap.java

/**
* Process given part as File part which is to be saved in temp dir with the given filename.
*/
private void processFilePart(Part part,String filename) throws IOException {
filename=filename.substring(filename.lastIndexOf('/') + 1).substring(filename.lastIndexOf('\\') + 1);
String prefix=filename;
String suffix="";
if (filename.contains(".")) {
prefix=filename.substring(0,filename.lastIndexOf('.'));
suffix=filename.substring(filename.lastIndexOf('.'));
}
File file=File.createTempFile(prefix + "_",suffix,new File(location));
if (multipartConfigured) {
part.write(file.getName());
}
else {
InputStream input=null;
OutputStream output=null;
try {
input=new BufferedInputStream(part.getInputStream(),DEFAULT_BUFFER_SIZE);
output=new BufferedOutputStream(new FileOutputStream(file),DEFAULT_BUFFER_SIZE);
byte[] buffer=new byte[DEFAULT_BUFFER_SIZE];
for (int length=0; ((length=input.read(buffer)) > 0); ) {
output.write(buffer,0,length);
}
}
finally {
if (output != null) try {
output.close();
}
catch ( IOException logOrIgnore) {
}
if (input != null) try {
input.close();
}
catch ( IOException logOrIgnore) {
}
}
}
put(part.getName(),file);
part.delete();
}

Example 16

  5 

From project jboss-as-quickstart, under directory /xml-dom4j/src/main/java/org/jboss/as/quickstart/xml/upload/, in source file FileUploadServlet.java

@Override protected void doPost(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException {
final String reqContentType=req.getContentType();
if (!reqContentType.contains("multipart/form-data")) {
logger.severe("Received request which is not mulipart: " + reqContentType);
resp.sendError(406,"Received request which is not mulipart: " + reqContentType);
return;
}
Collection<Part> fileParts=req.getParts();
if (fileParts != null && fileParts.size() > 0) {
for ( Part p : fileParts) {
String partContentType=p.getContentType();
String partName=p.getName();
if (partContentType != null && partContentType.equals("text/xml") && partName != null && partName.equals(INPUT_NAME)) {
InputStream is=p.getInputStream();
fileUploadBean.parseUpload(is);
break;
}
}
}
RequestDispatcher rd=getServletContext().getRequestDispatcher("/");
if (rd != null) {
rd.forward(req,resp);
return;
}
else {
throw new IllegalStateException("Container is not well!");
}
}

Example 17

  5 

From project jboss-as-quickstart, under directory /xml-jaxp/src/main/java/org/jboss/as/quickstart/xml/upload/, in source fileFileUploadServlet.java

@Override protected void doPost(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException {
final String reqContentType=req.getContentType();
if (!reqContentType.contains("multipart/form-data")) {
logger.severe("Received request which is not mulipart: " + reqContentType);
resp.sendError(406,"Received request which is not mulipart: " + reqContentType);
return;
}
Collection<Part> fileParts=req.getParts();
if (fileParts != null && fileParts.size() > 0) {
for ( Part p : fileParts) {
String partContentType=p.getContentType();
String partName=p.getName();
if (partContentType != null && partContentType.equals("text/xml") && partName != null && partName.equals(INPUT_NAME)) {
InputStream is=p.getInputStream();
fileUploadBean.parseUpload(is);
break;
}
}
}
RequestDispatcher rd=getServletContext().getRequestDispatcher("/");
if (rd != null) {
rd.forward(req,resp);
return;
}
else {
throw new IllegalStateException("Container is not well!");
}
}

Example 18

  5 

From project MiddlewareMagicDemos, under directory /EE6_FileUpload_Servlet/src/, in source file FileUploadServlet.java

public void service(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
PrintWriter out=response.getWriter();
out.println("<html><head><body>");
for ( Part part : request.getParts()) {
String fileName="";
String partHeader=part.getHeader("content-disposition");
long partSize=part.getSize();
out.println("<BR>Part Name = " + part.getName());
out.println("<BR>Part Header = " + partHeader);
out.println("<BR>Part Size = " + partSize);
System.out.println("part.getHeader(\"content-disposition\") = " + part.getHeader("content-disposition"));
}
out.println("<center><h1>File Upload Completed Successfully</h1></center></body></html>");
System.out.println("Custom Way To Upload File with Actual FileName.");
fileUploadWithDesiredFilePathAndName(request);
System.out.println("File Uploaded using custom Way.");
}

Example 19

  5 

From project spring-framework, under directory /spring-web/src/main/java/org/springframework/web/multipart/support/, in source file StandardMultipartHttpServletRequest.java

/**
* Create a new StandardMultipartHttpServletRequest wrapper for the given request.
* @param request the servlet request to wrap
* @throws MultipartException if parsing failed
*/
public StandardMultipartHttpServletRequest(HttpServletRequest request) throws MultipartException {
super(request);
try {
Collection<Part> parts=request.getParts();
MultiValueMap<String,MultipartFile> files=new LinkedMultiValueMap<String,MultipartFile>(parts.size());
for ( Part part : parts) {
String filename=extractFilename(part.getHeader(CONTENT_DISPOSITION));
if (filename != null) {
files.add(part.getName(),new StandardMultipartFile(part,filename));
}
}
setMultipartFiles(files);
}
catch ( Exception ex) {
throw new MultipartException("Could not parse multipart servlet request",ex);
}
}

Example 20

  5 

From project spring-framework, under directory /spring-web/src/main/java/org/springframework/web/multipart/support/, in source file StandardServletMultipartResolver.java

public void cleanupMultipart(MultipartHttpServletRequest request){
try {
for ( Part part : request.getParts()) {
if (request.getFile(part.getName()) != null) {
part.delete();
}
}
}
catch ( Exception ex) {
LogFactory.getLog(getClass()).warn("Failed to perform cleanup of multipart items",ex);
}
}

The examples above are mined from open source projects. Each example has a reference to 
its resource, but the http link may not be provided due to the evoluation of the project.

Java Code Examples for javax.servlet.http.Part的更多相关文章

  1. [转]Java Code Examples for android.util.JsonReader

    [转]Java Code Examples for android.util.JsonReader The following are top voted examples for showing h ...

  2. Exception in thread "main" java.lang.SecurityException: class "javax.servlet.FilterRegistration"'s signer information does not match signer information of other classes in the same package解决办法(图文详解)

    不多说,直接上干货! 问题详情 SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation. SLF ...

  3. java.lang.SecurityException: class "javax.servlet.AsyncContext"'s signer information does not match signer information of other classes in the same package

    最近在写个Http协议的压测挡板时,遇到以下错误. 2018-03-08 10:34:07.808:INFO:oejs.Server:jetty-8.1.9.v20130131 2018-03-08 ...

  4. Java Code Examples for org.codehaus.jackson.map.DeserializationConfig 配置

    The following code examples are extracted from open source projects. You can click  to vote up the e ...

  5. 2018.10.10 Java的The superclass "javax.servlet.http.HttpServlet" was not found on the Java Build Path 错误

    我们在用Eclipse进行Java web开发时,可能会出现这样的错误:The superclass javax.servlet.http.HttpServlet was not found on t ...

  6. Java Code Examples for PhantomJSDriverService

    Example 1 Project: thucydides   File: PhantomJSCapabilityEnhancer.java View source code Vote up 6 vo ...

  7. java.lang.SecurityException: class "javax.servlet.FilterRegistration"(spark下maven)

    今天写spark例子用到maven,但是自己maven又不熟悉.遇到错误找了半天知道是(sevlet-api2.5 3.0)包冲突需要解决包之间依赖问题却不知道怎么下手.但是最终慢慢了解还是找到新手的 ...

  8. Java Code Examples for org.springframework.http.HttpStatus

    http://www.programcreek.com/java-api-examples/index.php?api=org.springframework.http.HttpStatus

  9. Java Code Examples for org.apache.ibatis.annotations.Insert

    http://www.programcreek.com/java-api-examples/index.php?api=org.apache.ibatis.annotations.Insert htt ...

随机推荐

  1. 是什么时候开始学习gulp了

    转自:http://www.ydcss.com/archives/18 简介: gulp是前端开发过程中对代码进行构建的工具,是自动化项目的构建利器:她不仅能对网站资源进行优化,而且在开发过程中很多重 ...

  2. SD卡状态广播

    SD状态发生改变的时候会对外发送广播.SD卡的状态一般有挂载.未挂载和无SD卡. 清单文件 一个广播接受者可以接受多条广播.这里在意图过滤器中添加是data属性是因为广播也需要进行匹配的.对方发送的广 ...

  3. pageEncoding与contentType属性

    1图例分析 由图中可以看出,这个两个属性没有任何关系. 把这两个设置成不同的编码格式对中文显示不会产生任何影响 2.原因分析 pageEncoding规定了以什么编码方式存储和读取,使两者保持一致性, ...

  4. TCP/UDP,SOCKET网络通信,C++/Java实现

    趁这两天没事干,就把网络通信这一块搞一搞,C/S方面的了解一下,很重要! TCP Server/Client

  5. 不停止MySQL服务的情况下修改root的密码

    首先我们得知道一个MySQL普通用户的密码 这里我来记录一下我的操作过程 这里我刚刚到一家公司上面装的是cacti,但是之前的运维不记得MySQL的root密码了 但是他知道cacti的密码, 用户: ...

  6. mysql 数据库隔离级别

    select @@tx_isolation; 4种隔离级别 1.read uncommitted 2.read committed 3.repeatable read(MySQL默认隔离级别) 4.  ...

  7. poj3177 && poj3352 边双连通分量缩点

    Redundant Paths Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 12676   Accepted: 5368 ...

  8. Eclipse自动调整格式

    Eclipse 编写Java代码的时候,使用右键Source -> Format 后,将自动调整格式,若想要{ 单独占一行,则可以自己定义相关格式模板 新建 CodeFormatter.xml ...

  9. 数据库开发基础-SQl Server 链接查询

    连接查询:通过连接运算符可以实现多个表查询.连接是关系数据库模型的主要特点,也是它区别于其它类型数据库管理系统的一个标志. 常用的两个链接运算符: 1.join   on 2.union     在关 ...

  10. HTML基础及一般标签

    HTML        内容 Hyper Text Markup Language  超文本标记语言(包含文本.表格.图片.声音.视频等,同时也是文档) HTML 元素指的是从开始标签(start t ...