本文整理汇总了Java中org.apache.commons.fileupload.FileItem.getName方法的典型用法代码示例。如果您正苦于以下问题:Java FileItem.getName方法的具体用法?Java FileItem.getName怎么用?Java FileItem.getName使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类org.apache.commons.fileupload.FileItem
的用法示例。
在下文中一共展示了FileItem.getName方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: processUploadedFile
import org.apache.commons.fileupload.FileItem; //导入方法依赖的package包/类
/**
* 解析上传域
*
* @param item 文件对象
* @return {@link FileFormResult}
* @throws IOException IO异常
*/
private FileFormResult processUploadedFile(FileItem item) throws IOException {
String name = item.getName();
String fileSuffix = FilenameUtils.getExtension(name);
if (CollectionUtils.isNotEmpty(allowedSuffixList) && !allowedSuffixList.contains(fileSuffix)) {
throw new NotAllowedUploadException(String.format("上传文件格式不正确,fileName=%s,allowedSuffixList=%s",
name, allowedSuffixList));
}
FileFormResult file = new FileFormResult();
file.setFieldName(item.getFieldName());
file.setFileName(name);
file.setContentType(item.getContentType());
file.setSizeInBytes(item.getSize());
//如果未设置上传路径,直接保存到项目根目录
if (Strings.isNullOrEmpty(baseDir)) {
baseDir = request.getRealPath("/");
}
File relativePath = new File(SEPARATOR + DateFormatUtils.format(new Date(), "yyyyMMdd") + file.getFileName());
FileCopyUtils.copy(item.getInputStream(), new FileOutputStream(relativePath));
file.setSaveRelativePath(relativePath.getAbsolutePath());
return file;
}
示例2: processFileField
import org.apache.commons.fileupload.FileItem; //导入方法依赖的package包/类
protected void processFileField(FileItem item) {
LOG.debug("Item is a file upload");
// Skip file uploads that don't have a file name - meaning that no file was selected.
if (item.getName() == null || item.getName().trim().length() < 1) {
LOG.debug("No file has been uploaded for the field: {}", item.getFieldName());
return;
}
List<FileItem> values;
if (files.get(item.getFieldName()) != null) {
values = files.get(item.getFieldName());
} else {
values = new ArrayList<>();
}
values.add(item);
files.put(item.getFieldName(), values);
}
示例3: FileData
import org.apache.commons.fileupload.FileItem; //导入方法依赖的package包/类
FileData(FileItem item)
{
this.fileName = item.getName();
this.type = item.getContentType();
this.data = item.get();
if(fileName != null)
{
int i = fileName.lastIndexOf("/");
if(i>0)
{
fileName = fileName.substring(i+1);
}
else
{
i = fileName.lastIndexOf("\\");
if(i>0)
{
fileName = fileName.substring(i+1);
}
}
}
this.item = item;
}
示例4: executePost
import org.apache.commons.fileupload.FileItem; //导入方法依赖的package包/类
public void executePost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String path = getPath(request);
String thePath = fileBasePath+"uploads/"; //TODO calculate the directory path for this file
/////////////////////////////
//TODO: thePath will be dependent on a verb retrieved from request
/////////////////////////////
String verb = getVerb(path);
String userId = "";
if (verb.equals("uUpload") ||
verb.equals("muUpload")) {
System.out.println("UserUpload "+thePath);
//user upload
userId = getUserId(path);
String tempPath = thePath+userId;
File dir = new File(tempPath);
if (!dir.exists()) {
boolean foo = dir.mkdir();
System.out.println("MADEDIR "+foo);
}
thePath = dir.getAbsolutePath();
}
try {
System.out.println("UPLOADING TO "+verb+" | "+userId+" | "+thePath);
File repository = new File(thePath);
String uploadPath = repository.getAbsolutePath()+"/";
DiskFileItemFactory dfiFactory = dfiFactory = new DiskFileItemFactory();
dfiFactory.setRepository(repository);
ServletFileUpload servletFileUpload = new ServletFileUpload(dfiFactory);
System.out.println("PARSING");
List<FileItem> items = servletFileUpload.parseRequest(request);
System.out.println("FILEUPLOADING "+path+
" | "+items.size());
Iterator<FileItem> iter = items.iterator();
while (iter.hasNext()) {
FileItem item = iter.next();
String fileName = item.getName();
if (item.isFormField()) {
//TODO processFormField(item);
} else {
//TODOprocessUploadedFile(item);
File f = new File(uploadPath+fileName);
item.write(f);
}
//TODO would be nice to have a socket and show progress
} } catch (Exception e) {
environment.logError(e.getMessage(), e);
e.printStackTrace();
}
if (verb.equals("uUpload"))
response.sendRedirect("/gui");
else
sendHTML("ok", response);
}
示例5: handleRequestInternal
import org.apache.commons.fileupload.FileItem; //导入方法依赖的package包/类
@RequestMapping(method = RequestMethod.POST)
protected ModelAndView handleRequestInternal(HttpServletRequest request) throws Exception {
String username = securityService.getCurrentUsername(request);
// Check that we have a file upload request.
if (!ServletFileUpload.isMultipartContent(request)) {
throw new Exception("Illegal request.");
}
Map<String, Object> map = new HashMap<String, Object>();
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List<?> items = upload.parseRequest(request);
// Look for file items.
for (Object o : items) {
FileItem item = (FileItem) o;
if (!item.isFormField()) {
String fileName = item.getName();
byte[] data = item.get();
if (StringUtils.isNotBlank(fileName) && data.length > 0) {
createAvatar(fileName, data, username, map);
} else {
map.put("error", new Exception("Missing file."));
LOG.warn("Failed to upload personal image. No file specified.");
}
break;
}
}
map.put("username", username);
map.put("avatar", settingsService.getCustomAvatar(username));
return new ModelAndView("avatarUploadResult","model",map);
}
示例6: 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();
}
}
示例7: doUpload
import org.apache.commons.fileupload.FileItem; //导入方法依赖的package包/类
@Override
protected void doUpload(HttpServletRequest request, Document document, FileItem item) throws Exception {
File fullFile = new File(item.getName());
String certifNameExtension=fullFile.getName().replaceFirst(".*\\.", ".");
if(CertificateManager.isCertificateExtension(certifNameExtension)){
File savedFile = new File(getRepository(), fullFile.getName());
item.write(savedFile);
ServiceUtils.addMessage(document, document.getDocumentElement(), "The certificate \""+fullFile.getName()+"\" has been successfully uploaded", "message", false);
}
else{
ServiceUtils.addMessage(document, document.getDocumentElement(), "The extension \""+certifNameExtension+"\" isn't valid", "error", false);
}
}
示例8: execute
import org.apache.commons.fileupload.FileItem; //导入方法依赖的package包/类
@Override
public FileUploadRpcResponse execute(FileUploadRpcRequest request, SessionContext helper) {
if (request.isReset()) {
helper.setAttribute(UploadServlet.SESSION_LAST_FILE, null);
return new FileUploadRpcResponse();
} else {
FileItem file = (FileItem)helper.getAttribute(UploadServlet.SESSION_LAST_FILE);
return (file == null ? new FileUploadRpcResponse() : new FileUploadRpcResponse(file.getName()));
}
}
示例9: receiveFile
import org.apache.commons.fileupload.FileItem; //导入方法依赖的package包/类
@SuppressWarnings({ "unchecked" })
private void receiveFile(HttpServletRequest request, OnFileReceiveListener listener) throws Exception{
DiskFileItemFactory factory = new DiskFileItemFactory();
// 临时文件夹路径
String repositoryPath = ConfigManager.getManager().FILE_TEMP_PATH;
// 设定临时文件夹为repositoryPath
File fileTempFolder = new File(repositoryPath);
if(!fileTempFolder.exists())fileTempFolder.mkdirs();
factory.setRepository(fileTempFolder);
// 设定上传文件的阈值,如果上传文件大于1M,就可能在repository
// 所代 表的文件夹中产生临时文件,否则直接在内存中进行处理
factory.setSizeThreshold(1024 * 1024);
// 创建一个ServletFileUpload对象
ServletFileUpload uploader = new ServletFileUpload(factory);
// 调用uploader中的parseRequest方法,可以获得请求中的相关内容,
// 即一个FileItem类型的ArrayList。FileItem是在
// org.apache.commons.fileupload中定义的,它可以代表一个文件,
// 也可以代表一个普通的form field
ArrayList<FileItem> list = (ArrayList<FileItem>) uploader.parseRequest(request);
for (FileItem fileItem : list){
if (!fileItem.isFormField()){ // 如果是文件
String fileName = fileItem.getName() + UUID.randomUUID();
// 将其中包含的内容写到指定目录下名为fileName的文件中
File file = new File(ConfigManager.getManager().FILE_SAVE_PATH + File.separator + fileName);
file.createNewFile();
// System.out.println(file.getPath());
fileItem.write(file);
listener.onFinished(MD5.getMD5CodeByFile(file),fileName,file.length());
break;//一次请求只接受一个文件
}
}
}
示例10: 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();
}
示例11: 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;
}
示例12: 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();
}
}
}
示例13: getFile
import org.apache.commons.fileupload.FileItem; //导入方法依赖的package包/类
private InputStream getFile(VariablesSecureApp vars) throws IOException {
FileItem fi = vars.getMultiFile("inpFile");
if (fi == null)
throw new IOException("Invalid filename");
filename = fi.getName();
InputStream in = fi.getInputStream();
if (in == null)
throw new IOException("Corrupted file");
return in;
}
示例14: handleRequestInternal
import org.apache.commons.fileupload.FileItem; //导入方法依赖的package包/类
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
String username = securityService.getCurrentUsername(request);
// Check that we have a file upload request.
if (!ServletFileUpload.isMultipartContent(request)) {
throw new Exception("Illegal request.");
}
Map<String, Object> map = new HashMap<String, Object>();
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List<?> items = upload.parseRequest(request);
// Look for file items.
for (Object o : items) {
FileItem item = (FileItem) o;
if (!item.isFormField()) {
String fileName = item.getName();
byte[] data = item.get();
if (StringUtils.isNotBlank(fileName) && data.length > 0) {
createAvatar(fileName, data, username, map);
} else {
map.put("error", new Exception("Missing file."));
LOG.warn("Failed to upload personal image. No file specified.");
}
break;
}
}
map.put("username", username);
map.put("avatar", settingsService.getCustomAvatar(username));
ModelAndView result = super.handleRequestInternal(request, response);
result.addObject("model", map);
return result;
}
示例15: 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;
}