本文整理汇总了Java中org.apache.commons.fileupload.FileItem.getFieldName方法的典型用法代码示例。如果您正苦于以下问题:Java FileItem.getFieldName方法的具体用法?Java FileItem.getFieldName怎么用?Java FileItem.getFieldName使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类org.apache.commons.fileupload.FileItem
的用法示例。
在下文中一共展示了FileItem.getFieldName方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: importProject
import org.apache.commons.fileupload.FileItem; //导入方法依赖的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");
}
示例2: importExcelTemplate
import org.apache.commons.fileupload.FileItem; //导入方法依赖的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);
}
示例3: addFileParameter
import org.apache.commons.fileupload.FileItem; //导入方法依赖的package包/类
/**
* <p> Adds a file parameter to the set of file parameters for this
* request and also to the list of all parameters. </p>
*
* @param item The file item for the parameter to add.
*/
protected void addFileParameter(FileItem item) {
FormFile formFile = new CommonsFormFile(item);
String name = item.getFieldName();
if (elementsFile.containsKey(name)) {
Object o = elementsFile.get(name);
if (o instanceof List) {
((List)o).add(formFile);
} else {
List list = new ArrayList();
list.add((FormFile)o);
list.add(formFile);
elementsFile.put(name, list);
elementsAll.put(name, list);
}
} else {
elementsFile.put(name, formFile);
elementsAll.put(name, formFile);
}
}
示例4: processFormField
import org.apache.commons.fileupload.FileItem; //导入方法依赖的package包/类
/**
* Process multipart request item as regular form field. The name and value
* of each regular form field will be added to the given parameterMap.
*
* @param formField The form field to be processed.
* @param parameterMap The parameterMap to be used for the HttpServletRequest.
*/
private void processFormField(FileItem formField, Map<String, String[]> parameterMap) {
String name = formField.getFieldName();
String value = formField.getString();
String[] values = parameterMap.get(name);
if (values == null) {
// Not in parameter map yet, so add as new value.
parameterMap.put(name, new String[]{value});
} else {
// Multiple field values, so add new value to existing array.
int length = values.length;
String[] newValues = new String[length + 1];
System.arraycopy(values, 0, newValues, 0, length);
newValues[length] = value;
parameterMap.put(name, newValues);
}
}
示例5: uploadFiles
import org.apache.commons.fileupload.FileItem; //导入方法依赖的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;
}
示例6: multipartHandler
import org.apache.commons.fileupload.FileItem; //导入方法依赖的package包/类
@Override
public Map<String, String[]> multipartHandler() throws Exception {
multipart = new Multipart();
DiskFileItemFactory disk = new DiskFileItemFactory();
ServletFileUpload servletFileUpload = new ServletFileUpload(disk);
List<FileItem> items = servletFileUpload.parseRequest(wrapper.httpRequest());
Map<String, String[]> params = new HashMap<>();
for (FileItem fileItem : items) {
if (fileItem.isFormField()) {
String fieldName = fileItem.getFieldName();
String fieldVal = fileItem.getString("UTF-8");
String[] param = params.get(fieldName);
if (param != null) {
String[] newArray = new String[param.length + 1];
System.arraycopy(param, 0, newArray, 0, param.length);
newArray[param.length] = fieldVal;
param = newArray;
} else {
param = new String[]{fieldVal};
}
params.put(fieldName, param);
}
else {
multipart.addFiles(fileItem);
}
}
return params;
}
示例7: HttpUploadReader
import org.apache.commons.fileupload.FileItem; //导入方法依赖的package包/类
HttpUploadReader(FileItem item) throws IOException {
this.item = item;
fieldName = item.getFieldName();
fileName = item.getName();
contentType = item.getContentType();
size = item.getSize();
inputStream = item.getInputStream();
}
示例8: initFields
import org.apache.commons.fileupload.FileItem; //导入方法依赖的package包/类
/**
* 处理上传内容
*
* @param request
* @param maxSize
* @return
*/
// @SuppressWarnings("unchecked")
private Map<String, Object> initFields(HttpServletRequest request) {
// 存储表单字段和非表单字段
Map<String, Object> map = new HashMap<String, Object>();
// 第一步:判断request
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
// 第二步:解析request
if (isMultipart) {
// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();
// 阀值,超过这个值才会写到临时目录,否则在内存中
factory.setSizeThreshold(1024 * 1024 * 10);
factory.setRepository(new File(tempPath));
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("UTF-8");
// 最大上传限制
upload.setSizeMax(maxSize);
/* FileItem */
List<FileItem> items = null;
// Parse the request
try {
items = upload.parseRequest(request);
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 第3步:处理uploaded items
if (items != null && items.size() > 0) {
Iterator<FileItem> iter = items.iterator();
// 文件域对象
List<FileItem> list = new ArrayList<FileItem>();
// 表单字段
Map<String, String> fields = new HashMap<String, String>();
while (iter.hasNext()) {
FileItem item = iter.next();
// 处理所有表单元素和文件域表单元素
if (item.isFormField()) { // 表单元素
String name = item.getFieldName();
String value = item.getString();
fields.put(name, value);
} else { // 文件域表单元素
list.add(item);
}
}
map.put(FORM_FIELDS, fields);
map.put(FILE_FIELDS, list);
}
}
return map;
}
示例9: performImport
import org.apache.commons.fileupload.FileItem; //导入方法依赖的package包/类
private String performImport(List<FileItem> files) {
//import certificate
String status = "";
InputStream filecontent = null;
Integer id = null;
try {
for (FileItem item : files) {
if (!item.isFormField()) {
// Process form file field (input type="file").
filecontent = item.getInputStream();
} else {
// Process regular form field (input type="text|radio|checkbox|etc", select, etc).
String fieldname = item.getFieldName();
String fieldvalue = item.getString();
if (fieldname.equals("id")) {
id = Integer.parseInt(fieldvalue);
}
}
}
if (id != null && filecontent != null) {
status = importCertificates(id, filecontent);
}
} catch (Exception ex) {
LOGGER.info(ex);
}
return "/sharingcenter/security/import.jsp?id=" + id + "&" + status;
}
示例10: processTextField
import org.apache.commons.fileupload.FileItem; //导入方法依赖的package包/类
private void processTextField(FileItem item, DocFile docFile) {
String name = item.getFieldName();
String value = item.getString();
if ("rn".equals(name))
docFile.setRn(Integer.parseInt(value));
else if ("filename".equals(name))
docFile.setFilename(value);
else if ("uploader".equals(name))
docFile.setUploader(value);
else if ("contentType".equals(name))
docFile.setContentType(value);
}
示例11: doPost
import org.apache.commons.fileupload.FileItem; //导入方法依赖的package包/类
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
try {
List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
String fileName = null;
String filePath = null;
String path = null;
InputStream fileContent = null;
for (FileItem item : items) {
if (!item.isFormField()) {
fileContent = item.getInputStream();
fileName = FilenameUtils.getName(item.getName());
}else if (item.isFormField() && item.getFieldName() != null
&& item.getFieldName().equals("filePath")){
path = item.getString();
}
}
filePath = path + File.separator + fileName;
OutputStream dest = new FileOutputStream(new
File(filePath));
int read = 0;
byte[] bytes = new byte[1024];
while ((read = fileContent.read(bytes)) != -1) {
dest.write(bytes, 0, read);
}
fileContent.close();
dest.close();
} catch (FileUploadException e) {
e.printStackTrace();
throw new ServletException("Cannot parse multipart request.", e);
}
index(request, response);
}
示例12: getParameterMapForMultipart
import org.apache.commons.fileupload.FileItem; //导入方法依赖的package包/类
/**
* File Uploadがある場合のパラメータ解析を行います。
* @param req HTTPリクエスト。
* @return パラメータ解析結果。
* @throws Exception 例外。
*/
private Map<String, Object> getParameterMapForMultipart(final HttpServletRequest req) throws Exception {
Map<String, Object> map = new HashMap<String, Object>();
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setRepository(new File(tempDir)); //一時的に保存する際のディレクトリ
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding(encoding);
@SuppressWarnings("unchecked")
List<FileItem> list = upload.parseRequest(req);
for (FileItem item : list) {
String key = item.getFieldName();
if (key != null) {
if (item.isFormField()) {
String value = item.getString(encoding);
this.addParamMap(map, key, value);
} else {
String filename = item.getName();
if (StringUtil.isBlank(filename)) {
map.put(key, null);
} else {
map.put(key, item);
}
}
}
}
return map;
}
示例13: processRequest
import org.apache.commons.fileupload.FileItem; //导入方法依赖的package包/类
public Object processRequest(HttpServletRequest request) throws Exception {
HttpServletRequestTwsWrapper twsRequest = request instanceof HttpServletRequestTwsWrapper ? (HttpServletRequestTwsWrapper) request : null;
File temporaryFile = null;
try {
// Check multipart request
if (ServletFileUpload.isMultipartContent(request)) {
Engine.logContext.debug("(ServletRequester.initContext) Multipart resquest");
// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();
// Set factory constraints
factory.setSizeThreshold(1000);
temporaryFile = File.createTempFile("c8o-multipart-files", ".tmp");
int cptFile = 0;
temporaryFile.delete();
temporaryFile.mkdirs();
factory.setRepository(temporaryFile);
Engine.logContext.debug("(ServletRequester.initContext) Temporary folder for upload is : " + temporaryFile.getAbsolutePath());
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// Set overall request size constraint
upload.setSizeMax(EnginePropertiesManager.getPropertyAsLong(PropertyName.FILE_UPLOAD_MAX_REQUEST_SIZE));
upload.setFileSizeMax(EnginePropertiesManager.getPropertyAsLong(PropertyName.FILE_UPLOAD_MAX_FILE_SIZE));
// Parse the request
List<FileItem> items = GenericUtils.cast(upload.parseRequest(request));
for (FileItem fileItem : items) {
String parameterName = fileItem.getFieldName();
String parameterValue;
if (fileItem.isFormField()) {
parameterValue = fileItem.getString();
Engine.logContext.trace("(ServletRequester.initContext) Value for field '" + parameterName + "' : " + parameterValue);
} else {
String name = fileItem.getName().replaceFirst("^.*(?:\\\\|/)(.*?)$", "$1");
if (name.length() > 0) {
File wDir = new File(temporaryFile, "" + (++cptFile));
wDir.mkdirs();
File wFile = new File(wDir, name);
fileItem.write(wFile);
fileItem.delete();
parameterValue = wFile.getAbsolutePath();
Engine.logContext.debug("(ServletRequester.initContext) Temporary uploaded file for field '" + parameterName + "' : " + parameterValue);
} else {
Engine.logContext.debug("(ServletRequester.initContext) No temporary uploaded file for field '" + parameterName + "', empty name");
parameterValue = "";
}
}
if (twsRequest != null) {
twsRequest.addParameter(parameterName, parameterValue);
}
}
}
Requester requester = getRequester();
request.setAttribute("convertigo.requester", requester);
Object result = requester.processRequest(request);
processRequestEnd(request, requester);
return result;
} finally {
if (temporaryFile != null) {
try {
Engine.logEngine.debug("(GenericServlet) Removing the temporary file : " + temporaryFile.getAbsolutePath());
FileUtils.deleteDirectory(temporaryFile);
} catch (IOException e) { }
}
}
}
示例14: addTextParameter
import org.apache.commons.fileupload.FileItem; //导入方法依赖的package包/类
/**
* Adds a regular text parameter to the set of text parameters for this
* request and also to the list of all parameters. Handles the case of
* multiple values for the same parameter by using an array for the
* parameter value.
*
* @param request The request in which the parameter was specified.
* @param item The file item for the parameter to add.
*/
protected void addTextParameter(HttpServletRequest request, FileItem item) {
String name = item.getFieldName();
String value = null;
boolean haveValue = false;
String encoding = request.getCharacterEncoding();
if (encoding != null) {
try {
value = item.getString(encoding);
haveValue = true;
} catch (Exception e) {
// Handled below, since haveValue is false.
}
}
if (!haveValue) {
try {
value = item.getString("ISO-8859-1");
} catch (java.io.UnsupportedEncodingException uee) {
value = item.getString();
}
haveValue = true;
}
if (request instanceof MultipartRequestWrapper) {
MultipartRequestWrapper wrapper = (MultipartRequestWrapper) request;
wrapper.setParameter(name, value);
}
String[] oldArray = (String[]) elementsText.get(name);
String[] newArray;
if (oldArray != null) {
newArray = new String[oldArray.length + 1];
System.arraycopy(oldArray, 0, newArray, 0, oldArray.length);
newArray[oldArray.length] = value;
} else {
newArray = new String[] { value };
}
elementsText.put(name, newArray);
elementsAll.put(name, newArray);
}
示例15: execute
import org.apache.commons.fileupload.FileItem; //导入方法依赖的package包/类
@SuppressWarnings("unchecked")
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
// cumberstone way of extracting POSTed form with a file
DiskFileUpload formParser = new DiskFileUpload();
formParser.setRepositoryPath(Configuration.get(ConfigurationKeys.LAMS_TEMP_DIR));
List<FileItem> formFields = formParser.parseRequest(request);
String returnURL = null;
String limitTypeParam = null;
InputStream uploadedFileStream = null;
String packageName = null;
for (FileItem formField : formFields) {
String fieldName = formField.getFieldName();
if ("returnURL".equals(fieldName)) {
// this can be empty; if so, another method of delivering results is used
returnURL = formField.getString();
} else if ("limitType".equals(fieldName)) {
limitTypeParam = formField.getString();
} else if ("file".equals(fieldName) && !StringUtils.isBlank(formField.getName())) {
packageName = formField.getName().toLowerCase();
uploadedFileStream = formField.getInputStream();
}
}
// this parameter is not really used at the moment
request.setAttribute("returnURL", returnURL);
// show only chosen types of questions
request.setAttribute("limitType", limitTypeParam);
// user did not choose a file
if ((uploadedFileStream == null) || !(packageName.endsWith(".zip") || packageName.endsWith(".xml"))) {
ActionMessages errors = new ActionMessages();
errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("label.questions.file.missing"));
request.setAttribute(Globals.ERROR_KEY, errors);
return mapping.findForward("questionFile");
}
Set<String> limitType = null;
if (!StringUtils.isBlank(limitTypeParam)) {
limitType = new TreeSet<String>();
// comma delimited acceptable question types, for example "mc,fb"
Collections.addAll(limitType, limitTypeParam.split(","));
}
Question[] questions = packageName.endsWith(".xml")
? QuestionParser.parseQTIFile(uploadedFileStream, null, limitType)
: QuestionParser.parseQTIPackage(uploadedFileStream, limitType);
request.setAttribute("questions", questions);
return mapping.findForward("questionChoice");
}