本文整理汇总了Java中org.apache.commons.fileupload.FileItemStream.getName方法的典型用法代码示例。如果您正苦于以下问题:Java FileItemStream.getName方法的具体用法?Java FileItemStream.getName怎么用?Java FileItemStream.getName使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类org.apache.commons.fileupload.FileItemStream
的用法示例。
在下文中一共展示了FileItemStream.getName方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: processFileItemStreamAsFileField
import org.apache.commons.fileupload.FileItemStream; //导入方法依赖的package包/类
/**
* Processes the FileItemStream as a file field.
*
* @param itemStream file item stream
* @param location location
*/
private void processFileItemStreamAsFileField(FileItemStream itemStream, String location) {
// Skip file uploads that don't have a file name - meaning that no file was selected.
if (itemStream.getName() == null || itemStream.getName().trim().length() < 1) {
LOG.debug("No file has been uploaded for the field: {}", itemStream.getFieldName());
return;
}
File file = null;
try {
// Create the temporary upload file.
file = createTemporaryFile(itemStream.getName(), location);
if (streamFileToDisk(itemStream, file)) {
createFileInfoFromItemStream(itemStream, file);
}
} catch (IOException e) {
if (file != null) {
try {
file.delete();
} catch (SecurityException se) {
LOG.warn("Failed to delete '{}' due to security exception above.", file.getName(), se);
}
}
}
}
示例2: createFileInfoFromItemStream
import org.apache.commons.fileupload.FileItemStream; //导入方法依赖的package包/类
/**
* Creates an internal <code>FileInfo</code> structure used to pass information
* to the <code>FileUploadInterceptor</code> during the interceptor stack
* invocation process.
*
* @param itemStream file item stream
* @param file the file
*/
private void createFileInfoFromItemStream(FileItemStream itemStream, File file) {
// gather attributes from file upload stream.
String fileName = itemStream.getName();
String fieldName = itemStream.getFieldName();
// create internal structure
FileInfo fileInfo = new FileInfo(file, itemStream.getContentType(), fileName);
// append or create new entry.
if (!fileInfos.containsKey(fieldName)) {
List<FileInfo> infos = new ArrayList<>();
infos.add(fileInfo);
fileInfos.put(fieldName, infos);
} else {
fileInfos.get(fieldName).add(fileInfo);
}
}
示例3: uploadFile
import org.apache.commons.fileupload.FileItemStream; //导入方法依赖的package包/类
/**
* Uploads a file to Google Cloud Storage to the bucket specified in the BUCKET_NAME
* environment variable, appending a timestamp to end of the uploaded filename.
*/
public String uploadFile(FileItemStream fileStream, final String bucketName)
throws IOException, ServletException {
checkFileExtension(fileStream.getName());
DateTimeFormatter dtf = DateTimeFormat.forPattern("-YYYY-MM-dd-HHmmssSSS");
DateTime dt = DateTime.now(DateTimeZone.UTC);
String dtString = dt.toString(dtf);
final String fileName = fileStream.getName() + dtString;
// the inputstream is closed by default, so we don't need to close it here
@SuppressWarnings("deprecation")
BlobInfo blobInfo =
storage.create(
BlobInfo
.newBuilder(bucketName, fileName)
// Modify access list to allow all users with link to read file
.setAcl(new ArrayList<>(Arrays.asList(Acl.of(User.ofAllUsers(), Role.READER))))
.build(),
fileStream.openStream());
logger.log(Level.INFO, "Uploaded file {0} as {1}", new Object[]{
fileStream.getName(), fileName});
// return the public download link
return blobInfo.getMediaLink();
}
示例4: uploadFile
import org.apache.commons.fileupload.FileItemStream; //导入方法依赖的package包/类
/**
* Uploads a file to Google Cloud Storage to the bucket specified in the BUCKET_NAME
* environment variable, appending a timestamp to end of the uploaded filename.
*/
@SuppressWarnings("deprecation")
public String uploadFile(FileItemStream fileStream, final String bucketName)
throws IOException, ServletException {
checkFileExtension(fileStream.getName());
DateTimeFormatter dtf = DateTimeFormat.forPattern("-YYYY-MM-dd-HHmmssSSS");
DateTime dt = DateTime.now(DateTimeZone.UTC);
String dtString = dt.toString(dtf);
final String fileName = fileStream.getName() + dtString;
// the inputstream is closed by default, so we don't need to close it here
BlobInfo blobInfo =
storage.create(
BlobInfo
.newBuilder(bucketName, fileName)
// Modify access list to allow all users with link to read file
.setAcl(new ArrayList<>(Arrays.asList(Acl.of(User.ofAllUsers(), Role.READER))))
.build(),
fileStream.openStream());
// return the public download link
return blobInfo.getMediaLink();
}
示例5: uploadFile
import org.apache.commons.fileupload.FileItemStream; //导入方法依赖的package包/类
/**
* Uploads a file to Google Cloud Storage to the bucket specified in the BUCKET_NAME
* environment variable, appending a timestamp to end of the uploaded filename.
*/
public String uploadFile(FileItemStream fileStream, final String bucketName)
throws IOException, ServletException {
checkFileExtension(fileStream.getName());
DateTimeFormatter dtf = DateTimeFormat.forPattern("-YYYY-MM-dd-HHmmssSSS");
DateTime dt = DateTime.now(DateTimeZone.UTC);
String dtString = dt.toString(dtf);
final String fileName = fileStream.getName() + dtString;
// the inputstream is closed by default, so we don't need to close it here
@SuppressWarnings("deprecation")
BlobInfo blobInfo =
storage.create(
BlobInfo
.newBuilder(bucketName, fileName)
// Modify access list to allow all users with link to read file
.setAcl(new ArrayList<>(Arrays.asList(Acl.of(User.ofAllUsers(), Role.READER))))
.build(),
fileStream.openStream());
// return the public download link
return blobInfo.getMediaLink();
}
示例6: execute
import org.apache.commons.fileupload.FileItemStream; //导入方法依赖的package包/类
@Override
protected void execute(ElfinderStorage elfinderStorage, HttpServletRequest request, JSONObject json) throws Exception {
List<FileItemStream> files = (List<FileItemStream>) request.getAttribute(FileItemStream.class.getName());
List<VolumeHandler> added = new ArrayList<>();
String target = request.getParameter(ElFinderConstants.ELFINDER_PARAMETER_TARGET);
VolumeHandler parentDir = findTarget(elfinderStorage, target);
for (FileItemStream file : files) {
String fileName = file.getName();
VolumeHandler newFile = new VolumeHandler(parentDir, fileName);
newFile.createFile();
InputStream is = file.openStream();
OutputStream os = newFile.openOutputStream();
IOUtils.copy(is, os);
os.close();
is.close();
added.add(newFile);
}
json.put(ElFinderConstants.ELFINDER_JSON_RESPONSE_ADDED, buildJsonFilesArray(request, added));
}
示例7: _store
import org.apache.commons.fileupload.FileItemStream; //导入方法依赖的package包/类
private ISObject _store(FileItemStream fileItemStream) throws IOException {
String filename = fileItemStream.getName();
String key = newKey(filename);
File tmpFile = getFile(key);
InputStream input = fileItemStream.openStream();
ThresholdingByteArrayOutputStream output = new ThresholdingByteArrayOutputStream(inMemoryCacheThreshold, tmpFile);
IO.copy(input, output);
ISObject retVal;
if (output.exceedThreshold) {
retVal = getFull(key);
} else {
int size = output.written;
byte[] buf = output.buf();
retVal = SObject.of(key, buf, size);
}
if (S.notBlank(filename)) {
retVal.setFilename(filename);
}
String contentType = fileItemStream.getContentType();
if (null != contentType) {
retVal.setContentType(contentType);
}
return retVal;
}
示例8: fileItemStreamToByteArray
import org.apache.commons.fileupload.FileItemStream; //导入方法依赖的package包/类
public static byte[] fileItemStreamToByteArray(FileItemStream item, int docType) throws IOException, FileUploadException {
if (item != null && docType > 0) {
byte[] array = IOUtils.toByteArray(item.openStream());
String[] types = new String[0];
boolean returnVal = false;
if (docType == 1) {
types = new String[]{".jpg", ".jpeg", ".png"};
} else if (docType == 2) {
types = new String[]{".pdf", ".doc", ".docx"};
} else if (docType == 3) {
types = new String[]{".pdf", ".jpg", ".jpeg", ".png"};
}
for (String type : types) {
if (getFileType(item).contains(type)) {
returnVal = true;
}
}
if (item.getName() != null && returnVal) {
return array;
}
}
throw new InvalidFormatException();
}
示例9: initialiseUpload
import org.apache.commons.fileupload.FileItemStream; //导入方法依赖的package包/类
private void initialiseUpload()
throws Throwable {
try {
FileItemStream lCurrentItem = mMultipartUploadReader.getUploadFileItem();
if(lCurrentItem == null) {
throw new ExInternal("No file available on the multipart upload reader - either reader is in an invalid state, or the upload contained no file field");
}
mItemInputStream = lCurrentItem.openStream();
if (lCurrentItem.isFormField()) {
//Skip form fields, they should have been read by the MultipartUploadReader
Track.alert("UploadWorkItem", "Unexpected form field encountered when streaming upload");
}
else {
mItemNonBlockingInputStream = new NonBlockingInputStream(mItemInputStream, BYTE_READ_QUANTITY, MAX_SUBSEQUENT_BUFFER_READS);
String lFilename = lCurrentItem.getName();
mUploadInfo.setOriginalFileLocation(lFilename);
int lBeginningIndex = lFilename.lastIndexOf("\\");
if ( lFilename != null && lBeginningIndex != -1 ) {
// substr from that last occurrence of a back slash
lFilename = lFilename.substring(lBeginningIndex + 1);
}
mUploadInfo.setFilename(lFilename);
String lContentType = lCurrentItem.getContentType();
mUploadInfo.setBrowserContentType(lContentType != null ? lContentType : "" );
mStatus = READING_FILE_DATA;
mLastReadTime = System.currentTimeMillis();
}
}
catch (Throwable ex1) {
throw ex1;
}
}
示例10: processFileItem
import org.apache.commons.fileupload.FileItemStream; //导入方法依赖的package包/类
private void processFileItem(RequestState state, FileItemStream item) throws ServletException, IOException {
File uploadDir = ensureUploadDirectory();
if (uploadDir != null) {
File uploadFile = null;
try {
String prefix = UPLOAD_FILE_PREFIX;
String suffix = UPLOAD_FILE_SUFFIX;
uploadFile = File.createTempFile(prefix, suffix, uploadDir);
InputStream is = null;
InputStream bis = null;
OutputStream bos = null;
try {
is = item.openStream();
bis = new BufferedInputStream(is, UPLOAD_BUFFER_SIZE);
bos = new BufferedOutputStream(new FileOutputStream(uploadFile), UPLOAD_BUFFER_SIZE);
byte[] buffer = new byte[UPLOAD_BUFFER_SIZE];
int fileLength = 0;
for (int nb = 0; (nb = bis.read(buffer)) >= 0;) {
if (nb > 0) {
bos.write(buffer, 0, nb);
fileLength += nb;
}
}
state.uploadFile = uploadFile;
state.uploadFileLength = fileLength;
state.uploadFileNameOriginal = item.getName();
if (state.uploadFileNameOriginal == null)
state.uploadFileNameOriginal = "unspecified";
} finally {
StreamUtil.closeSafely(bos);
StreamUtil.closeSafely(bis);
StreamUtil.closeSafely(is);
}
} catch (IOException e) {
state.setPreverifyException(e);
}
}
}
示例11: asMultipartRequest
import org.apache.commons.fileupload.FileItemStream; //导入方法依赖的package包/类
private static MultipartRequest asMultipartRequest(HttpServletRequest request) throws Exception {
String encoding = request.getCharacterEncoding();
MultipartRequest req = new MultipartRequest(request);
ServletFileUpload upload = new ServletFileUpload();
upload.setHeaderEncoding(encoding);
FileItemIterator it = upload.getItemIterator(request);
while (it.hasNext()) {
FileItemStream item = it.next();
String fieldName = item.getFieldName();
InputStream stream = item.openStream();
try {
if (item.isFormField()) {
req.setParameter(fieldName, Streams.asString(stream, encoding));
} else {
String originalFilename = item.getName();
File diskFile = getTempFile(originalFilename);
OutputStream fos = new FileOutputStream(diskFile);
try {
IoUtils.copy(stream, fos);
} finally {
IoUtils.closeQuietly(fos);
}
FilePart filePart = new FilePart(fieldName, originalFilename, diskFile);
req.addFile(filePart);
}
} finally {
IoUtils.closeQuietly(stream);
}
}
return req;
}
示例12: FormPart
import org.apache.commons.fileupload.FileItemStream; //导入方法依赖的package包/类
public FormPart(FileItemStream stream) {
fieldName = stream.getFieldName();
contentType = stream.getContentType();
binaryContent = readBinaryContent(stream);
fileName = stream.getName();
if(contentType == null || contentType.contains(MediaType.TEXT_PLAIN)) {
textContent = new String(binaryContent);
}
}
示例13: doPost
import org.apache.commons.fileupload.FileItemStream; //导入方法依赖的package包/类
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Creates EntityManager to query database
EntityManager em = EMFUtil.getEMFactory().createEntityManager();
// Transactions are employed to roll back changes in case of error and
// ensure data integrity
EntityTransaction trans = em.getTransaction();
// Creates a session object and retrieves entities
HttpSession session = request.getSession();
int candidateID = (int) session.getAttribute("candidateID");
Candidates candidate = em.find(Candidates.class, candidateID);
String source = request.getParameter("source");
System.out.println(source);
ServletFileUpload upload = new ServletFileUpload();
try {
FileItemIterator iterator = upload.getItemIterator(request);
while (iterator.hasNext()) {
FileItemStream item = iterator.next();
if (item.getName() != null) {
if (item.getName().contains(".pdf") || item.getName().contains(".doc")) {
byte[] file = IOUtils.toByteArray(item.openStream());
candidate.setResume(file);
trans.begin();
em.merge(candidate);
trans.commit();
// For logging activity
SchoolLoginLogs loginLog = (SchoolLoginLogs) session.getAttribute("loginLog");
if (loginLog != null) {
SchoolActivityLogs activityLog = new SchoolActivityLogs();
activityLog.setSchoolLoginLogID(loginLog.getSchoolLoginLogID());
activityLog.setTime(Clock.getCurrentTime());
activityLog.setCandidateID(candidateID);
activityLog.setCandidate(candidate);
activityLog.setSchoolActivity("Uploaded Resume");
SchoolAccountDataAccessObject.persistActivityLog(activityLog);
}
session.setAttribute("resumeSuccess", "Resume uploaded!");
session.setAttribute("resume", "true");
session.setAttribute("candidate", candidate);
session.setAttribute("loginLog", loginLog);
} else {
String resumeError = "Please upload a resume in PDF or DOC/DOCX format.";
session.setAttribute("resume", "true");
session.setAttribute("resumeError", resumeError);
}
}
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("Error uploading resume");
} finally {
em.close();
response.sendRedirect("schools/school-candidate-profile.jsp");
}
}
示例14: doPost
import org.apache.commons.fileupload.FileItemStream; //导入方法依赖的package包/类
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
EntityManager em = EMFUtil.getEMFactory().createEntityManager();
EntityTransaction trans = em.getTransaction();
HttpSession session = request.getSession();
int candidateID = (int) session.getAttribute("candidateID");
Candidates candidate = em.find(Candidates.class, candidateID);
ServletFileUpload upload = new ServletFileUpload();
try {
FileItemIterator iterator = upload.getItemIterator(request);
while (iterator.hasNext()) {
FileItemStream item = iterator.next();
if (item.getName() != null) {
if (item.getName().toLowerCase().contains(".jpg") || item.getName().toLowerCase().contains(".jpeg")
|| item.getName().toLowerCase().contains(".png")) {
byte[] file = IOUtils.toByteArray(item.openStream());
candidate.setPhoto(file);
trans.begin();
candidate = em.merge(candidate);
trans.commit();
session.setAttribute("resume", "true");
session.setAttribute("resumeSuccess", "Picture uploaded!");
session.setAttribute("candidate", candidate);
// For logging activity
SchoolLoginLogs loginLog = (SchoolLoginLogs) session.getAttribute("loginLog");
if (loginLog != null) {
SchoolActivityLogs activityLog = new SchoolActivityLogs();
activityLog.setSchoolLoginLogID(loginLog.getSchoolLoginLogID());
activityLog.setTime(Clock.getCurrentTime());
activityLog.setCandidateID(candidateID);
activityLog.setCandidate(candidate);
activityLog.setSchoolActivity("Uploaded Picture");
SchoolAccountDataAccessObject.persistActivityLog(activityLog);
}
session.setAttribute("resume", "true");
session.setAttribute("resumeSuccess", "Picture uploaded!");
session.setAttribute("candidate", candidate);
response.sendRedirect("schools/school-candidate-profile.jsp");
} else {
String resumeError = "Please upload a picture in PNG or JPG/JPEG format.";
session.setAttribute("resume", "true");
session.setAttribute("resumeError", resumeError);
response.sendRedirect("schools/school-candidate-profile.jsp");
}
}
}
} catch (Exception e) {
e.printStackTrace();
session.setAttribute("resumeError", "An error occurred.");
response.sendRedirect("schools/school-candidate-profile.jsp");
} finally {
em.close();
}
}
示例15: uploadFiles
import org.apache.commons.fileupload.FileItemStream; //导入方法依赖的package包/类
/**
* 파일을 Upload 처리한다.
*
* @param request
* @param where
* @param maxFileSize
* @return
* @throws Exception
*/
public static List<FormBasedFileVo> uploadFiles(
HttpServletRequest request,
String where,
long maxFileSize) throws Exception {
List<FormBasedFileVo> list = new ArrayList<FormBasedFileVo>();
// Check that we have a file upload request
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart) {
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload();
upload.setFileSizeMax(maxFileSize); // SizeLimitExceededException
// Parse the request
FileItemIterator iter = upload.getItemIterator(request);
while (iter.hasNext()) {
FileItemStream item = iter.next();
String name = item.getFieldName();
InputStream stream = item.openStream();
if (item.isFormField()) {
// System.out.println("Form field '" + name + "' with value '" + Streams.asString(stream) +
// "' detected.");
LOG.info("Form field '" + name + "' with value '" + Streams.asString(stream) + "' detected.");
} else {
// System.out.println("File field '" + name + "' with file name '" + item.getName() + "' detected.");
LOG.info("File field '" + name + "' with file name '" + item.getName() + "' detected.");
if ("".equals(item.getName())) {
continue;
}
// Process the input stream
FormBasedFileVo vo = new FormBasedFileVo();
String tmp = item.getName();
if (tmp.lastIndexOf("\\") >= 0) {
tmp = tmp.substring(tmp.lastIndexOf("\\") + 1);
}
vo.setFileName(tmp);
vo.setContentType(item.getContentType());
vo.setServerSubPath(getTodayString());
vo.setPhysicalName(getPhysicalFileName());
if (tmp.lastIndexOf(".") >= 0) {
vo.setPhysicalName(vo.getPhysicalName() + tmp.substring(tmp.lastIndexOf(".")));
}
long size = saveFile(stream,
new File(WebUtil.filePathBlackList(where) + SEPERATOR + vo.getServerSubPath() + SEPERATOR + vo.getPhysicalName()));
vo.setSize(size);
list.add(vo);
}
}
} else {
throw new IOException("form's 'enctype' attribute have to be 'multipart/form-data'");
}
return list;
}