本文整理汇总了Java中org.apache.commons.fileupload.servlet.ServletFileUpload类的典型用法代码示例。如果您正苦于以下问题:Java ServletFileUpload类的具体用法?Java ServletFileUpload怎么用?Java ServletFileUpload使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
ServletFileUpload类属于org.apache.commons.fileupload.servlet包,在下文中一共展示了ServletFileUpload类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: getFileItemList
import org.apache.commons.fileupload.servlet.ServletFileUpload; //导入依赖的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.ServletFileUpload; //导入依赖的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: upload
import org.apache.commons.fileupload.servlet.ServletFileUpload; //导入依赖的package包/类
/**
* 文件上传处理类
*
* @return {@link UploadResult}
* @throws Exception 抛出异常
*/
public UploadResult upload() throws Exception {
boolean multipartContent = ServletFileUpload.isMultipartContent(request);
if (!multipartContent) {
throw new RuntimeException("上传表单enctype类型设置错误");
}
List<TextFormResult> textFormResultList = Lists.newArrayList();
List<FileFormResult> fileFormResultList = Lists.newArrayList();
List<FileItem> fileItems = upload.parseRequest(request);
for (FileItem item : fileItems) {
if (item.isFormField())
textFormResultList.add(processFormField(item));
else
fileFormResultList.add(processUploadedFile(item));
}
return new UploadResult(textFormResultList, fileFormResultList);
}
示例4: getFileItemList
import org.apache.commons.fileupload.servlet.ServletFileUpload; //导入依赖的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;
}
示例5: getMultipartContentItems
import org.apache.commons.fileupload.servlet.ServletFileUpload; //导入依赖的package包/类
private List<FileItem> getMultipartContentItems() throws IOException, FileUploadException {
List<FileItem> items = null;
boolean isMultipart = ServletFileUpload.isMultipartContent(req);
if (isMultipart) {
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(0);
reposDir = new File(FileUtils.getTempDirectory(), File.separatorChar + UUID.randomUUID().toString());
if (!reposDir.mkdirs()) {
throw new XSLWebException(String.format("Could not create DiskFileItemFactory repository directory (%s)", reposDir.getAbsolutePath()));
}
factory.setRepository(reposDir);
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setSizeMax(1024 * 1024 * webApp.getMaxUploadSize());
items = upload.parseRequest(req);
}
return items;
}
示例6: parseRequestMultiPartItems
import org.apache.commons.fileupload.servlet.ServletFileUpload; //导入依赖的package包/类
/**
* Gets the FileItemIterator of the input.
*
* Can be used to process uploads in a streaming fashion. Check out:
* http://commons.apache.org/fileupload/streaming.html
*
* @return the FileItemIterator of the request or null if there was an
* error.
*/
public Optional<List<FormItem>> parseRequestMultiPartItems(String encoding) {
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(properties.getInt(Constants.PROPERTY_UPLOADS_MAX_SIZE/*Constants.Params.maxUploadSize.name()*/));//Configuration.getMaxUploadSize());
factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); //Configuration.getTmpDir());
//README the file for tmpdir *MIGHT* need to go into Properties
ServletFileUpload upload = new ServletFileUpload(factory);
if(encoding != null)
upload.setHeaderEncoding(encoding);
upload.setFileSizeMax(properties.getInt(Constants.PROPERTY_UPLOADS_MAX_SIZE));
try {
List<FormItem> items = upload.parseRequest(request)
.stream()
.map(item -> new ApacheFileItemFormItem(item))
.collect(Collectors.toList());
return Optional.of(items);
} catch (FileUploadException e) {
//"Error while trying to process mulitpart file upload"
//README: perhaps some logging
}
return Optional.empty();
}
示例7: extractBagFilesFromRequest
import org.apache.commons.fileupload.servlet.ServletFileUpload; //导入依赖的package包/类
private ArrayList<File> extractBagFilesFromRequest(@Context HttpServletRequest req,
@Context HttpServletResponse res) throws Exception {
File targetDir = null;
try {
File file = null;
DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
fileItemFactory.setSizeThreshold(1 * 1024 * 1024); // 1 MB
Iterator items = new ServletFileUpload(fileItemFactory).parseRequest(req).iterator();
while (items.hasNext()) {
FileItem item = (FileItem) items.next();
LOG.info("item Name = " + item.getName() + " ; content type = " + item.getContentType());
file = new File(FileUtils.getTempDirectory(), item.getName());
item.write(file);
}
targetDir = compressUtils.extractZippedBagFile(file.getAbsolutePath(), null);
LOG.info("extractedBagFileLocation " + targetDir);
} catch (IOException e) {
LOG.error("IOException", e);
sendResponseBag(res, e.getMessage(), "failure");
} catch (FormatHelper.UnknownFormatException unknownFormatException) {
LOG.error("unknownFormatException", unknownFormatException);
sendResponseBag(res, unknownFormatException.getMessage(), "failure");
}
return compressUtils.getAllFilesList(targetDir);
}
示例8: fileUpload
import org.apache.commons.fileupload.servlet.ServletFileUpload; //导入依赖的package包/类
/**
* 上传文件
*
* @param param
* @param request
* @return
* @throws Exception
*/
@RequestMapping(value = "/fileUpload", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity fileUpload(MultipartFileParam param, HttpServletRequest request) {
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart) {
logger.info("上传文件start。");
try {
// 方法1
//storageService.uploadFileRandomAccessFile(param);
// 方法2 这个更快点
storageService.uploadFileByMappedByteBuffer(param);
} catch (IOException e) {
e.printStackTrace();
logger.error("文件上传失败。{}", param.toString());
}
logger.info("上传文件end。");
}
return ResponseEntity.ok().body("上传成功。");
}
示例9: importProject
import org.apache.commons.fileupload.servlet.ServletFileUpload; //导入依赖的package包/类
public void importProject(HttpServletRequest req, HttpServletResponse resp) throws Exception {
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletContext servletContext = req.getSession().getServletContext();
File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
factory.setRepository(repository);
ServletFileUpload upload = new ServletFileUpload(factory);
InputStream inputStream=null;
boolean overwriteProject=true;
List<FileItem> items = upload.parseRequest(req);
if(items.size()==0){
throw new ServletException("Upload file is invalid.");
}
for(FileItem item:items){
String name=item.getFieldName();
if(name.equals("overwriteProject")){
String overwriteProjectStr=new String(item.get());
overwriteProject=Boolean.valueOf(overwriteProjectStr);
}else if(name.equals("file")){
inputStream=item.getInputStream();
}
}
repositoryService.importXml(inputStream,overwriteProject);
IOUtils.closeQuietly(inputStream);
resp.sendRedirect(req.getContextPath()+"/urule/frame");
}
示例10: importExcelTemplate
import org.apache.commons.fileupload.servlet.ServletFileUpload; //导入依赖的package包/类
public void importExcelTemplate(HttpServletRequest req, HttpServletResponse resp) throws Exception {
DiskFileItemFactory factory=new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List<FileItem> items = upload.parseRequest(req);
Iterator<FileItem> itr = items.iterator();
List<Map<String,Object>> mapData=null;
while (itr.hasNext()) {
FileItem item = (FileItem) itr.next();
String name=item.getFieldName();
if(!name.equals("file")){
continue;
}
InputStream stream=item.getInputStream();
mapData=parseExcel(stream);
httpSessionKnowledgeCache.put(req, IMPORT_EXCEL_DATA, mapData);
stream.close();
break;
}
httpSessionKnowledgeCache.put(req, IMPORT_EXCEL_DATA, mapData);
writeObjectToJson(resp, mapData);
}
示例11: getServiceResult
import org.apache.commons.fileupload.servlet.ServletFileUpload; //导入依赖的package包/类
protected void getServiceResult(HttpServletRequest request, Document document) throws Exception {
// Check that we have a file upload request
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (!isMultipart)
throw new IllegalArgumentException("Not multipart content!");
FileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// Parse the request
List<FileItem> items = GenericUtils.cast(upload.parseRequest(request));
// Process the uploaded items
handleFormFields(request);
for (FileItem item : items) {
doUpload(request, document, item);
}
}
示例12: isValidImage
import org.apache.commons.fileupload.servlet.ServletFileUpload; //导入依赖的package包/类
public static String isValidImage(HttpServletRequest request, MultipartFile file){
//最大文件大小
long maxSize = 5242880;
//定义允许上传的文件扩展名
HashMap<String, String> extMap = new HashMap<String, String>();
extMap.put("image", "gif,jpg,jpeg,png,bmp");
if(!ServletFileUpload.isMultipartContent(request)){
return "请选择文件";
}
if(file.getSize() > maxSize){
return "上传文件大小超过5MB限制";
}
//检查扩展名
String fileName=file.getOriginalFilename();
String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
if(!Arrays.<String>asList(extMap.get("image").split(",")).contains(fileExt)){
return "上传文件扩展名是不允许的扩展名\n只允许" + extMap.get("image") + "格式";
}
return "valid";
}
示例13: parseMultipartWithCommonsFileUpload
import org.apache.commons.fileupload.servlet.ServletFileUpload; //导入依赖的package包/类
private Collection<Part> parseMultipartWithCommonsFileUpload(HttpServletRequest request) throws IOException {
if (sharedFileItemFactory.get() == null) {
// Not a big deal if two threads actually set this up
DiskFileItemFactory fileItemFactory = new DiskFileItemFactory(
1 << 16, (File) servletContext.getAttribute("javax.servlet.context.tempdir"));
fileItemFactory.setFileCleaningTracker(
FileCleanerCleanup.getFileCleaningTracker(servletContext));
sharedFileItemFactory.compareAndSet(null, fileItemFactory);
}
try {
return new ServletFileUpload(sharedFileItemFactory.get()).parseRequest(request)
.stream().map(FileItemPart::new).collect(Collectors.toList());
} catch (FileUploadException e) {
throw new IOException(e.getMessage());
}
}
示例14: map
import org.apache.commons.fileupload.servlet.ServletFileUpload; //导入依赖的package包/类
public Map<String, Object> map(HttpServletRequest request) {
ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
upload.setSizeMax(20 * 1024);
upload.setFileSizeMax(10 * 1024);
List<FileItem> items;
try {
items = upload.parseRequest(request);
} catch (FileUploadException e) {
throw new RequestMappingException("", e);
}
return items.stream().map(item -> {
String key = item.getFieldName();
if (item.isFormField()) {
String value = item.getString();
return new SimpleKeyValue<String, Object>(key, value);
} else {
return new SimpleKeyValue<String, Object>(key, item);
}
}).collect(Collectors.toMap(
SimpleKeyValue::getKey,
SimpleKeyValue::getValue
));
}
示例15: VariablesBase
import org.apache.commons.fileupload.servlet.ServletFileUpload; //导入依赖的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();
}
}
}
}