本文整理匯總了Java中org.apache.commons.fileupload.FileItem.getString方法的典型用法代碼示例。如果您正苦於以下問題:Java FileItem.getString方法的具體用法?Java FileItem.getString怎麽用?Java FileItem.getString使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類org.apache.commons.fileupload.FileItem
的用法示例。
在下文中一共展示了FileItem.getString方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: getMultiParameters
import org.apache.commons.fileupload.FileItem; //導入方法依賴的package包/類
/**
* Retrieve a set of values belonging to a parameter passed to the servlet as part of a multi part
* content.
*
* @param parameter
* The name of the parameter to be retrieved.
* @param requestFilter
* filter used to validate the input against list of allowed inputs
* @return String array containing the values of the parameter. Empty string if the content is not
* multipart.
*/
public String[] getMultiParameters(String parameter, RequestFilter requestFilter) {
if (!isMultipart || items == null)
return null;
Iterator<FileItem> iter = items.iterator();
Vector<String> result = new Vector<String>();
while (iter.hasNext()) {
FileItem item = iter.next();
if (item.isFormField() && item.getFieldName().equals(parameter)) {
try {
String value = item.getString("UTF-8");
filterRequest(requestFilter, value);
result.addElement(value);
} catch (Exception ex) {
}
}
}
String[] strResult = new String[result.size()];
result.copyInto(strResult);
return strResult;
}
示例2: getMultiParameter
import org.apache.commons.fileupload.FileItem; //導入方法依賴的package包/類
/**
* Retrieve a parameter passed to the servlet as part of a multi part content.
*
* @param parameter
* the name of the parameter to be retrieved
* @param requestFilter
* filter used to validate the input against list of allowed inputs
* @return String containing the value of the parameter. Empty string if the content is not
* multipart or the parameter is not found.
*/
public String getMultiParameter(String parameter, RequestFilter requestFilter) {
if (!isMultipart || items == null)
return "";
Iterator<FileItem> iter = items.iterator();
while (iter.hasNext()) {
FileItem item = iter.next();
if (item.isFormField() && item.getFieldName().equals(parameter)) {
try {
String value = item.getString("UTF-8");
filterRequest(requestFilter, value);
return value;
} catch (Exception ex) {
ex.printStackTrace();
return "";
}
}
}
return "";
}
示例3: 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);
}
}
示例4: doGet
import org.apache.commons.fileupload.FileItem; //導入方法依賴的package包/類
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
try
{
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("UTF-8");
if (!ServletFileUpload.isMultipartContent(request))
{
return;
}
this.fileList = upload.parseRequest(request);
// System.out.println(fileList.size());
for (FileItem item : fileList)
{
if (item.isFormField())
{
String value = item.getString("UTF-8");
// System.out.print(value);
names.add(value);
} else
{
String filename = item.getName();
if (filename == null) continue;
File newFile = new File(filename);
// System.out.println(newFile.getCanonicalPath());
// item.write(newFile);
this.names.add(newFile.getAbsolutePath().toString());
saveFile(item);
}
}
} catch (Exception e)
{
e.printStackTrace();
}
}
示例5: 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;
}
示例6: 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;
}
示例7: processFileUpload
import org.apache.commons.fileupload.FileItem; //導入方法依賴的package包/類
/**
* Parse file and save.
*
* @param request request.
* @param saveDirectory save directory.
* @throws Exception may be.
*/
private void processFileUpload(HttpRequest request, File saveDirectory) throws Exception {
FileItemFactory factory = new DiskFileItemFactory(1024 * 1024, saveDirectory);
HttpFileUpload fileUpload = new HttpFileUpload(factory);
// Set upload process listener.
// fileUpload.setProgressListener(new ProgressListener(){...});
List<FileItem> fileItems = fileUpload.parseRequest(new HttpUploadContext((HttpEntityEnclosingRequest) request));
for (FileItem fileItem : fileItems) {
if (!fileItem.isFormField()) { // File param.
// Attribute.
// fileItem.getContentType();
// fileItem.getFieldName();
// fileItem.getName();
// fileItem.getSize();
// fileItem.getString();
File uploadedFile = new File(saveDirectory, fileItem.getName());
// 把流寫到文件上。
fileItem.write(uploadedFile);
} else { // General param.
String key = fileItem.getName();
String value = fileItem.getString();
}
}
}
示例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: 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;
}
示例10: parseFileItems
import org.apache.commons.fileupload.FileItem; //導入方法依賴的package包/類
protected MultipartParsingResult parseFileItems(List<FileItem> fileItems, String encoding) {
// System.out.println("fileItems:" + fileItems);
MultipartParsingResult result = super.parseFileItems(fileItems, encoding);
for (String fieldName : NAMES) {
if (result.getMultipartFiles().get(fieldName) != null) {
break;
}
FileItem item = this.find(fileItems, fieldName);
if (item == null) {
continue;
}
String content = item.getString();
// System.out.println("fieldName:" + fieldName + " content:" + content);
if (StringUtils.isEmpty(content)) {
continue;
}
if (!content.startsWith("data:image")) {
continue;
}
List<MultipartFile> list = this.toList(result, fieldName, content);
result.getMultipartFiles().put(fieldName, list);
// break;
}
// CommonsMultipartFile file = new CommonsMultipartFile(fileItem);
// multipartFiles.add(file.getName(), file);
return result;
}
示例11: 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;
}
示例12: 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);
}
示例13: 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);
}
示例14: createParam
import org.apache.commons.fileupload.FileItem; //導入方法依賴的package包/類
/**
* 創建請求對象
*/
public static Param createParam(HttpServletRequest request) throws IOException {
List<FormParam> formParamList = new ArrayList<FormParam>();
List<FileParam> fileParamList = new ArrayList<FileParam>();
try{
Map<String, List<FileItem>> fileItemListMap = servletFileUpload.parseParameterMap(request);
if (CollectionUtil.isNotEmpty(fileItemListMap)) {
for (Map.Entry<String, List<FileItem>> fileItemListEntry : fileItemListMap.entrySet()) {
String fieldName = fileItemListEntry.getKey();
List<FileItem> fileItemList = fileItemListEntry.getValue();
if (CollectionUtil.isNotEmpty(fileItemList)) {
for (FileItem fileItem : fileItemList) {
if(fileItem.isFormField()){
String fieldValue = fileItem.getString("UTF-8");
formParamList.add(new FormParam(fieldName, fieldValue));
} else{
String fileName = FileUtil.getRealFileName(new String(fileItem.getName().getBytes(), "UTF-8"));
if (StringUtil.isNotEmpty(fileName)) {
long fileSize = fileItem.getSize();
String contentType = fileItem.getContentType();
InputStream inputSteam = fileItem.getInputStream();
fileParamList.add(new FileParam(fieldName, fileName, fileSize, contentType, inputSteam));
}
}
}
}
}
}
}catch (FileUploadException e){
LOGGER.error("create param failure", e);
throw new RuntimeException(e);
}
return new Param(formParamList, fileParamList);
}
示例15: 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) { }
}
}
}