本文整理汇总了Java中org.apache.commons.fileupload.servlet.ServletRequestContext类的典型用法代码示例。如果您正苦于以下问题:Java ServletRequestContext类的具体用法?Java ServletRequestContext怎么用?Java ServletRequestContext使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
ServletRequestContext类属于org.apache.commons.fileupload.servlet包,在下文中一共展示了ServletRequestContext类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: getFileItemList
import org.apache.commons.fileupload.servlet.ServletRequestContext; //导入依赖的package包/类
/** 获取所有文本域 */
public static final List<?> getFileItemList(HttpServletRequest request, File saveDir) throws FileUploadException {
if (!saveDir.isDirectory()) {
saveDir.mkdir();
}
List<?> fileItems = null;
RequestContext requestContext = new ServletRequestContext(request);
if (FileUpload.isMultipartContent(requestContext)) {
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setRepository(saveDir);
factory.setSizeThreshold(fileSizeThreshold);
ServletFileUpload upload = new ServletFileUpload(factory);
fileItems = upload.parseRequest(request);
}
return fileItems;
}
示例2: getFileItemList
import org.apache.commons.fileupload.servlet.ServletRequestContext; //导入依赖的package包/类
/** 获取所有文本域 */
public static final List<?> getFileItemList(HttpServletRequest request, File saveDir) throws FileUploadException {
if (!saveDir.isDirectory()) {
saveDir.mkdir();
}
List<?> fileItems = null;
RequestContext requestContext = new ServletRequestContext(request);
if (FileUpload.isMultipartContent(requestContext)) {
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setRepository(saveDir);
factory.setSizeThreshold(fileSizeThreshold);
ServletFileUpload upload = new ServletFileUpload(factory);
fileItems = upload.parseRequest(request);
}
return fileItems;
}
示例3: getFileItemList
import org.apache.commons.fileupload.servlet.ServletRequestContext; //导入依赖的package包/类
/** 获取所有文本域 */
public static List<?> getFileItemList(HttpServletRequest request, File saveDir) throws FileUploadException {
if (!saveDir.isDirectory()) {
saveDir.mkdir();
}
List<?> fileItems = null;
RequestContext requestContext = new ServletRequestContext(request);
if (FileUpload.isMultipartContent(requestContext)) {
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setRepository(saveDir);
factory.setSizeThreshold(fileSizeThreshold);
ServletFileUpload upload = new ServletFileUpload(factory);
fileItems = upload.parseRequest(request);
}
return fileItems;
}
示例4: VariablesBase
import org.apache.commons.fileupload.servlet.ServletRequestContext; //导入依赖的package包/类
/**
* Basic constructor that takes the request object and saves it to be used by the subsequent
* methods
*
* @param request
* HttpServletRequest object originating from the user request.
*/
@SuppressWarnings("unchecked")
public VariablesBase(HttpServletRequest request) {
if (request == null) {
// logging exception to obtain stack trace to pinpoint the cause
log4j.warn("Creating a VariablesBase with a null request", new Exception());
this.session = new HttpSessionWrapper();
this.isMultipart = false;
} else {
this.session = request.getSession(true);
this.httpRequest = request;
this.isMultipart = ServletFileUpload.isMultipartContent(new ServletRequestContext(request));
if (isMultipart) {
DiskFileItemFactory factory = new DiskFileItemFactory();
// factory.setSizeThreshold(yourMaxMemorySize);
// factory.setRepositoryPath(yourTempDirectory);
ServletFileUpload upload = new ServletFileUpload(factory);
// upload.setSizeMax(yourMaxRequestSize);
try {
items = upload.parseRequest(request);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
示例5: extractAttachments
import org.apache.commons.fileupload.servlet.ServletRequestContext; //导入依赖的package包/类
/**
* extracts attachments from the http request.
*
* @param httpRequest
* request containing attachments DefaultMultipartHttpServletRequest is supported
* @param request
* {@link Request}
* @return ids of extracted attachments
* @throws IOException
* throws exception if problems during attachments accessing occurred
* @throws FileUploadException
* Exception.
* @throws AttachmentIsEmptyException
* Thrown, when the attachment is of zero size.
* @throws AuthorizationException
* in case there is no authenticated user
*/
private List<AttachmentResource> extractAttachments(HttpServletRequest httpRequest,
Request request) throws FileUploadException, IOException,
AttachmentIsEmptyException, AuthorizationException {
List<AttachmentResource> result = new ArrayList<>();
if (httpRequest.getContentType().startsWith(AttachmentResourceHelper.MULTIPART_FORM_DATA)) {
FileItemFactory factory = new DiskFileItemFactory();
FileUpload upload = new FileUpload(factory);
List<FileItem> items = upload.parseRequest(new ServletRequestContext(httpRequest));
for (FileItem file : items) {
if (!file.isFormField()) {
AttachmentTO attachmentTo = new AttachmentStreamTO(file.getInputStream(),
AttachmentStatus.UPLOADED);
AttachmentResourceHelper.assertAttachmentSize(file.getContentType(),
file.getSize(), false);
attachmentTo.setMetadata(new ContentMetadata());
attachmentTo.getMetadata().setFilename(getFileName(file.getName()));
attachmentTo.getMetadata().setContentSize(file.getSize());
result.add(persistAttachment(request, attachmentTo));
}
}
}
return result;
}
示例6: extractAttachments
import org.apache.commons.fileupload.servlet.ServletRequestContext; //导入依赖的package包/类
/**
* extracts attachments from the http request.
*
* @param httpRequest
* request containing attachments DefaultMultipartHttpServletRequest is supported
* @param request
* {@link Request}
* @return ids of extracted attachments
* @throws MaxLengthReachedException
* attachment size is to large
* @throws IOException
* throws exception if problems during attachments accessing occurred
* @throws FileUploadException
* Exception.
* @throws AttachmentIsEmptyException
* Thrown, when the attachment is of zero size.
* @throws AuthorizationException
* in case there is no authenticated user
*/
private List<AttachmentResource> extractAttachments(HttpServletRequest httpRequest,
Request request) throws MaxLengthReachedException, FileUploadException, IOException,
AttachmentIsEmptyException, AuthorizationException {
List<AttachmentResource> result = new ArrayList<AttachmentResource>();
if (httpRequest.getContentType().startsWith(AttachmentResourceHelper.MULTIPART_FORM_DATA)) {
FileItemFactory factory = new DiskFileItemFactory();
FileUpload upload = new FileUpload(factory);
List<FileItem> items = upload.parseRequest(new ServletRequestContext(httpRequest));
for (FileItem file : items) {
if (!file.isFormField()) {
AttachmentTO attachmentTo = new AttachmentStreamTO(file.getInputStream(),
AttachmentStatus.UPLOADED);
AttachmentResourceHelper.assertAttachmentSize(file.getContentType(),
file.getSize(), false);
attachmentTo.setMetadata(new ContentMetadata());
attachmentTo.getMetadata().setFilename(getFileName(file.getName()));
attachmentTo.getMetadata().setContentSize(file.getSize());
result.add(persistAttachment(request, attachmentTo));
}
}
}
return result;
}
示例7: extractAttachments
import org.apache.commons.fileupload.servlet.ServletRequestContext; //导入依赖的package包/类
/**
* extracts attachments from the http request.
*
* @param httpRequest
* request containing attachments DefaultMultipartHttpServletRequest is supported
* @param request
* {@link Request}
* @return ids of extracted attachments
* @throws MaxLengthReachedException
* attachment size is to large
* @throws IOException
* throws exception if problems during attachments accessing occurred
* @throws FileUploadException
* Exception.
* @throws AuthorizationException
* in case there is no authenticated user
*/
private List<AttachmentResource> extractAttachments(HttpServletRequest httpRequest,
Request request) throws MaxLengthReachedException, FileUploadException, IOException,
AuthorizationException {
List<AttachmentResource> result = new ArrayList<AttachmentResource>();
if (httpRequest.getContentType().startsWith(AttachmentResourceHelper.MULTIPART_FORM_DATA)) {
FileItemFactory factory = new DiskFileItemFactory();
FileUpload upload = new FileUpload(factory);
List<FileItem> items = upload.parseRequest(new ServletRequestContext(httpRequest));
for (FileItem file : items) {
if (!file.isFormField()) {
AttachmentTO attachmentTo = new AttachmentStreamTO(file.getInputStream(),
AttachmentStatus.UPLOADED);
AttachmentResourceHelper.assertAttachmentSize(file.getContentType(),
file.getSize(), false);
attachmentTo.setMetadata(new ContentMetadata());
attachmentTo.getMetadata().setFilename(getFileName(file.getName()));
attachmentTo.getMetadata().setContentSize(file.getSize());
result.add(persistAttachment(request, attachmentTo));
}
}
}
return result;
}
示例8: extractAttachments
import org.apache.commons.fileupload.servlet.ServletRequestContext; //导入依赖的package包/类
/**
* extracts attachments from the http request.
*
* @param httpRequest
* request containing attachments DefaultMultipartHttpServletRequest is supported
* @param request
* {@link Request}
* @return ids of extracted attachments
* @throws MaxLengthReachedException
* attachment size is to large
* @throws IOException
* throws exception if problems during attachments accessing occurred
* @throws FileUploadException
* Exception.
* @throws AuthorizationException
* in case there is no authenticated user
*/
private List<AttachmentResource> extractAttachments(HttpServletRequest httpRequest,
Request request) throws MaxLengthReachedException, FileUploadException, IOException,
AuthorizationException {
List<AttachmentResource> result = new ArrayList<AttachmentResource>();
if (httpRequest.getContentType().startsWith(AttachmentResourceHelper.MULTIPART_FORM_DATA)) {
FileItemFactory factory = new DiskFileItemFactory();
FileUpload upload = new FileUpload(factory);
List<FileItem> items = upload.parseRequest(new ServletRequestContext(httpRequest));
for (FileItem file : items) {
if (!file.isFormField()) {
AttachmentTO attachmentTo = new AttachmentStreamTO(file.getInputStream(),
AttachmentStatus.UPLOADED);
AttachmentResourceHelper.checkAttachmentSize(file);
attachmentTo.setMetadata(new ContentMetadata());
attachmentTo.getMetadata().setFilename(getFileName(file.getName()));
attachmentTo.getMetadata().setContentSize(file.getSize());
result.add(persistAttachment(request, attachmentTo));
}
}
}
return result;
}
示例9: uploadFiles
import org.apache.commons.fileupload.servlet.ServletRequestContext; //导入依赖的package包/类
/**
* @see http://www.oschina.net/code/snippet_698737_13402
* @param request
* @return
* @throws IOException
*/
public static Map<String, Object> uploadFiles(HttpServlet servlet, HttpServletRequest request) {
Map<String, Object> map = JwUtils.newHashMap();
Map<String, String> fileMap = JwUtils.newHashMap();
map.put("file", fileMap);
DiskFileItemFactory factory = new DiskFileItemFactory();// 创建工厂
factory.setSizeThreshold(1024 * 1024 * 30);// 设置最大缓冲区为30M
// 设置缓冲区目录
String savePath = servlet.getServletContext().getRealPath("/WEB-INF/temp");
factory.setRepository(new File(savePath));
FileUpload upload = new FileUpload(factory);// 获得上传解析器
upload.setHeaderEncoding("UTF-8");// 解决上传文件名乱码
try {
String targetFolderPath = servlet.getServletContext().getRealPath("/WEB-INF/" + ConfigUtils.getProperty("web.files.upload.folder"));
File targetFolder = new File(targetFolderPath);// 目标文件夹
if(!targetFolder.exists()) {
targetFolder.mkdir();
}
List<FileItem> fileItems = upload.parseRequest(new ServletRequestContext(request));// 解析请求体
for (FileItem fileItem : fileItems) {
if (fileItem.isFormField()) {// 判断是普通表单项还是文件上传项
String name = fileItem.getFieldName();// 表单名
String value = fileItem.getString("UTF-8");// 表单值
map.put(name, value);
} else {// 文件上传项
String fileName = fileItem.getName();// 获取文件名
if (StringUtils.isEmpty(fileName))// 判断是否上传了文件
continue;
// 截取文件名
int index = fileName.lastIndexOf("/");
if (index > -1) {
fileName = fileName.substring(index);
}
// 检查文件是否允许上传
index = fileName.lastIndexOf(".");
if (index > -1 && index < fileName.length() - 1) {
String ext = fileName.substring(index + 1).toLowerCase();
if (!ConfigUtils.getString("web.files.upload.extension").contains(";" + ext + ";")) {
LOGGER.warn("The file {} is not allowed to upload.", fileName);
continue;
}
}
// 生成唯一文件名,保留原文件名
String newFileName = UUID.randomUUID().toString();
// 将文件内容写到服务器端
String targetPath = targetFolderPath + "/" + newFileName;
File targetFile = new File(targetPath);// 目标文件
targetFile.createNewFile();
fileItem.write(targetFile);
fileItem.delete();// 删除临时文件
fileMap.put(fileName, newFileName);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return map;
}
示例10: preHandle
import org.apache.commons.fileupload.servlet.ServletRequestContext; //导入依赖的package包/类
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
if (request != null && ServletFileUpload.isMultipartContent(request)) {
ServletRequestContext ctx = new ServletRequestContext(request);
long requestSize = ctx.contentLength();
if (requestSize > maxSize) {
throw new MaxUploadSizeExceededException(maxSize);
}
}
return true;
}
示例11: parseRequest
import org.apache.commons.fileupload.servlet.ServletRequestContext; //导入依赖的package包/类
protected List parseRequest(ServletRequestContext requestContext) throws FileUploadException {
// Create a factory for disk-based file items
FileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// Parse the request
return upload.parseRequest(requestContext);
}
示例12: uploadFile
import org.apache.commons.fileupload.servlet.ServletRequestContext; //导入依赖的package包/类
protected File uploadFile(HttpServletRequest request,
String repoDir,
HttpServletResponse response,
String extension) throws FileUploadException {
response.setContentType("text/html; charset=utf-8");
ServletRequestContext servletRequestContext = new ServletRequestContext(request);
boolean isMultipart =
ServletFileUpload.isMultipartContent(servletRequestContext);
File uploadedFile = null;
if (isMultipart) {
try {
// Create a new file upload handler
List items = parseRequest(servletRequestContext);
// Process the uploaded items
for (Iterator iter = items.iterator(); iter.hasNext();) {
FileItem item = (FileItem) iter.next();
if (!item.isFormField()) {
String fileName = item.getName();
String fileExtension = fileName;
fileExtension = fileExtension.toLowerCase();
if (extension != null && !fileExtension.endsWith(extension)) {
throw new Exception(" Illegal file type. Only " +
extension + " files can be uploaded");
}
String fileNameOnly = getFileName(fileName);
uploadedFile = new File(repoDir, fileNameOnly);
item.write(uploadedFile);
}
}
} catch (Exception e) {
String msg = "File upload failed";
log.error(msg, e);
throw new FileUploadException(msg, e);
}
}
return uploadedFile;
}
示例13: isMultipart
import org.apache.commons.fileupload.servlet.ServletRequestContext; //导入依赖的package包/类
@Override
public boolean isMultipart(HttpServletRequest request) {
// support HTTP PUT operation
String method = request.getMethod().toLowerCase();
if (S.neq("post", method) && S.neq("put", method)) {
return false;
}
return FileUploadBase.isMultipartContent(new ServletRequestContext(request));
}
示例14: parseFileUpload
import org.apache.commons.fileupload.servlet.ServletRequestContext; //导入依赖的package包/类
protected Map<String, String[]> parseFileUpload() {
//log.debug("parseFileUpload");
Map<String, String[]> parameters = new Hashtable<String, String[]>();
if (portletRequest instanceof HttpServletRequest) {
HttpServletRequest hreq = (HttpServletRequest) portletRequest;
//logRequestParameters();
//logRequestAttributes();
ServletRequestContext ctx = new ServletRequestContext(hreq);
if (FileUpload.isMultipartContent(ctx)) {
FileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
try {
fileItems = upload.parseRequest(hreq);
} catch (Exception e) {
log.error("Unable to parse multi part form!!!", e);
}
if (fileItems != null) {
//log.debug("File items has size " + fileItems.size());
for (int i = 0; i < fileItems.size(); i++) {
FileItem item = (FileItem) fileItems.get(i);
String[] tmpstr = new String[1];
if (item.isFormField()) {
tmpstr[0] = item.getString();
} else {
tmpstr[0] = "fileinput";
}
//log.debug("File item " + item.getFieldName() + "->" + tmpstr[0]);
parameters.put(item.getFieldName(), tmpstr);
}
}
}
}
return parameters;
}
示例15: getStreams
import org.apache.commons.fileupload.servlet.ServletRequestContext; //导入依赖的package包/类
/**
*
* @param req
* @param rpcRequest
* @param service
* @return
* @throws Exception
*/
private Map<String, InputStream> getStreams(HttpServletRequest req, RpcRequest rpcRequest, HttpAction service) throws Exception {
if (!FileUploadBase.isMultipartContent(new ServletRequestContext(req))) {
return null;
}
int streamsNumber = getInputStreamsNumber(rpcRequest, service);
boolean isResponseStreamed = service.isBinaryResponse();
FileItemIterator iter = (FileItemIterator) req.getAttribute(REQ_ATT_MULTIPART_ITERATOR);
int count = 0;
final Map<String, InputStream> map = new HashMap();
final File tempDirectory;
if (streamsNumber > 1 || streamsNumber == 1 && isResponseStreamed) {
tempDirectory = createTempUploadDirectory();
req.setAttribute(REQ_ATT_TEMPORARY_FOLDER, tempDirectory);
} else {
tempDirectory = null;
}
FileItemStream item = (FileItemStream) req.getAttribute(REQ_ATT_MULTIPART_CURRENT_ITEM);
long availableLength = RpcConfig.getInstance().getMaxRequestSize();
while (item != null) {
count++;
long maxLength = Math.min(availableLength, RpcConfig.getInstance().getMaxFileSize());
if (count < streamsNumber || isResponseStreamed) { // if response is streamed all inputstreams have to be readed first
File file = new File(tempDirectory, item.getFieldName());
FileOutputStream fos = new FileOutputStream(file);
try {
Miscellaneous.pipeSynchronously(new LimitedLengthInputStream(item.openStream(), maxLength), fos);
} catch (MaxLengthExceededException ex) {
if (maxLength == RpcConfig.getInstance().getMaxFileSize()) {
throw new MaxLengthExceededException("Upload part '" + item.getFieldName() + "' exceeds maximum length (" + RpcConfig.getInstance().getMaxFileSize() + " bytes)", RpcConfig.getInstance().getMaxFileSize());
} else {
throw new MaxLengthExceededException("Request exceeds maximum length (" + RpcConfig.getInstance().getMaxRequestSize() + " bytes)", RpcConfig.getInstance().getMaxRequestSize());
}
}
map.put(item.getFieldName(), new MetaDataInputStream(new FileInputStream(file), item.getName(), item.getContentType(), file.length(), null));
availableLength -= file.length();
} else if (count == streamsNumber) {
map.put(item.getFieldName(), new MetaDataInputStream(new LimitedLengthInputStream(item.openStream(), maxLength), item.getName(), item.getContentType(), null, null));
break;
}
req.setAttribute(REQ_ATT_MULTIPART_CURRENT_ITEM, item);
if (iter.hasNext()) {
item = iter.next();
} else {
item = null;
}
}
if (count != streamsNumber) {
throw new IllegalArgumentException("Invalid multipart request received. Number of uploaded files (" + count + ") does not match expected (" + streamsNumber + ")");
}
return map;
}