本文整理汇总了Java中org.apache.commons.fileupload.FileItem.write方法的典型用法代码示例。如果您正苦于以下问题:Java FileItem.write方法的具体用法?Java FileItem.write怎么用?Java FileItem.write使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类org.apache.commons.fileupload.FileItem
的用法示例。
在下文中一共展示了FileItem.write方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: handle
import org.apache.commons.fileupload.FileItem; //导入方法依赖的package包/类
@Override
public void handle( List<FileItem> fileItems )
{
for ( FileItem file : fileItems )
{
byte[] fileName = file.getName().getBytes();
try
{
String uploadName = new String( fileName, "utf-8" );
System.out.println( uploadName );
File writeFile = new File( "D:\\" + uploadName );
file.write( writeFile );
} catch ( Exception e )
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
示例2: store
import org.apache.commons.fileupload.FileItem; //导入方法依赖的package包/类
public static void store(DocFile doc, FileItem fileItem) {
String fullPath = getFullPath(doc);
File file = new File(fullPath);
if (file.isFile()) {
log.warn("File " + fullPath + " exists: will be overwritten!");
}
File dir = file.getParentFile();
if (!dir.exists()) {
dir.mkdirs();
log.info("Creating directory " + dir.getAbsolutePath());
}
try {
fileItem.write(file);
} catch (Exception ex) {
log.fatal(ex);
}
}
示例3: 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);
}
}
示例4: saveFileItem
import org.apache.commons.fileupload.FileItem; //导入方法依赖的package包/类
private void saveFileItem(FileItem item) throws Exception {
String[] fileNameParts = new File(item.getName()).getName().split("\\" +
".");
String suffix = "." + fileNameParts[1];
String prefix = fileNameParts[0];
File storeFile = File.createTempFile(prefix, suffix);
item.write(storeFile);
log.info("UPLOADED FILE IS - " + storeFile.getAbsolutePath());
}
示例5: 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;//一次请求只接受一个文件
}
}
}
示例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: 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);
}
示例9: upload
import org.apache.commons.fileupload.FileItem; //导入方法依赖的package包/类
/**
* Upload a file into the given directory.
*
* @param request
* - the HttpServletRequest object
* @param response
* - the HttpServletResponse object
* @param dir
* - the directory in which the files/directories are deleted
* @param fileItemList
* - the list with the uploaded files
*/
private void upload(HttpServletRequest request, File dir,
List<FileItem> fileItemList) {
if (fileItemList == null) {
return;
}
// Process the uploaded items
Iterator<FileItem> it = fileItemList.iterator();
while (it.hasNext()) {
FileItem item = it.next();
// Process a file upload
if (!item.isFormField()) {
String name = item.getName();
int i = name.lastIndexOf("/");
if (i < 0) {
i = name.lastIndexOf("\\");
}
if (i >= 0) {
name = name.substring(i + 1);
}
File file = new File(dir, name);
if (isAccessible(request, file)) {
try {
item.write(file);
BssClient bssClient = new BssClient(
request.getRemoteHost());
bssClient
.recordEvent(
getSaasId(request),
ProvisioningServiceSkeleton.EVENT_ID_FILE_UPLOAD,
getUserId(request), MULTIPLIER);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
示例10: 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) { }
}
}
}
示例11: doUpload
import org.apache.commons.fileupload.FileItem; //导入方法依赖的package包/类
protected void doUpload(HttpServletRequest request, Document document, FileItem item) throws Exception {
File fullFile = new File(item.getName());
File savedFile = new File(getRepository(), fullFile.getName());
item.write(savedFile);
}
示例12: doPost
import org.apache.commons.fileupload.FileItem; //导入方法依赖的package包/类
/**
* Metóda doPost je obslužná metóda, ktorá sa volá po vyvolaní daného servletu na strane používateľa.
* Pričom sa servlet vykonáva na strane servera.
* @param request - objekt požiadavky, ktorý sa prenáša zo strany klienta na stranu servera
* @param response - objekt odozvy servera, ktorý sa prenáša zo strany servera na stranu klienta
* @throws ServletException
* @throws IOException
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<FileItem> items = null;
try {
items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
} catch (FileUploadException e) {
throw new ServletException("Cannot parse multipart request.", e);
}
for (FileItem item : items) {
if (item.isFormField()) {
// Process regular form fields here the same way as request.getParameter().
// You can get parameter name by item.getFieldName();
// You can get parameter value by item.getString();
//System.out.println(items.size());
//trackName = items.get(0).getString();
//System.out.println(items.get(0).getString());
} else {
//System.out.println(item.getName());
try {
HttpSession session = request.getSession();
session.setAttribute("isMultimedia", "True");
String trackName = session.getAttribute("trackName").toString();
if(system.startsWith("Windows")){
path = Constants.USER_DATA_STORAGE + session.getAttribute("username") + "\\" + "Temp" + "\\" + "Multimedia" + "\\";
//path = "E:\\SCHOOL\\TUKE\\DIPLOMOVKA\\PRAKTICKA CAST\\GITHUB\\GPSWebApp\\web\\Logged\\uploaded_from_server\\" + session.getAttribute("username") + "\\" + "Temp" + "\\" + "Multimedia" + "\\";
}else{
path = Constants.USER_DATA_STORAGE + session.getAttribute("username") + "/" + "Temp" + "/" + "Multimedia" + "/";
}
new File(path).mkdirs();
String tmpFileName = Normalizer.normalize(item.getName(), Normalizer.Form.NFD);
String fileNameTMP = tmpFileName.replaceAll("[^\\x00-\\x7F]", "");
String fileName = fileNameTMP.replaceAll("[,|;]", "");
System.out.println("SUBORIK: " + fileName);
item.write(new File(path, fileName));
FileLogger.getInstance().createNewLog("Successfuly uploaded multimedia file " + fileName + " in user's " + session.getAttribute("username") + " track " + trackName + " .");
if(item.getName().toLowerCase().endsWith(".jpg") || item.getName().toLowerCase().endsWith(".jpeg")){
ImageResizer resizer = new ImageResizer(1024, 720);
//System.out.println("Resized> " + path + item.getName());
resizer.resizeImageWithTempThubnails(path + fileName);
}
} catch (Exception ex) {
System.out.println("Error: Cannot save multimedia files!");
FileLogger.getInstance().createNewLog("ERROR: Cannot upload multimedia files for user " + request.getSession().getAttribute("username") + " !!!");
}
}
}
//Show result page.
//request.getRequestDispatcher("HomePage.jsp").forward(request, response);
}
示例13: getFileParameterValue
import org.apache.commons.fileupload.FileItem; //导入方法依赖的package包/类
/**
* Responsible for constructing a FileBean object for the named file parameter. If there is no
* file parameter with the specified name this method should return null.
*
* @param name the name of the file parameter
* @return a FileBean object wrapping the uploaded file
*/
public FileBean getFileParameterValue(String name) {
final FileItem item = this.files.get(name);
if (item == null
|| ((item.getName() == null || item.getName().length() == 0) && item.getSize() == 0)) {
return null;
}
else {
// Attempt to ensure the file name is just the basename with no path included
String filename = item.getName();
int index;
if (WINDOWS_PATH_PREFIX_PATTERN.matcher(filename).find())
index = filename.lastIndexOf('\\');
else
index = filename.lastIndexOf('/');
if (index >= 0 && index + 1 < filename.length() - 1)
filename = filename.substring(index + 1);
// Use an anonymous inner subclass of FileBean that overrides all the
// methods that rely on having a File present, to use the FileItem
// created by commons upload instead.
return new FileBean(null, item.getContentType(), filename, this.charset) {
@Override public long getSize() { return item.getSize(); }
@Override public InputStream getInputStream() throws IOException {
return item.getInputStream();
}
@Override public void save(File toFile) throws IOException {
try {
item.write(toFile);
delete();
}
catch (Exception e) {
if (e instanceof IOException) throw (IOException) e;
else {
IOException ioe = new IOException("Problem saving uploaded file.");
ioe.initCause(e);
throw ioe;
}
}
}
@Override
public void delete() throws IOException { item.delete(); }
};
}
}
示例14: insert
import org.apache.commons.fileupload.FileItem; //导入方法依赖的package包/类
private OBError insert(VariablesSecureApp vars, String strFileReference, String tableId,
String key, String strDataType, String strText, String documentOrganization)
throws IOException, ServletException {
String cFileId = strFileReference, fileDir = null, path = null;
OBError myMessage = null;
myMessage = new OBError();
myMessage.setTitle("");
if (log4j.isDebugEnabled())
log4j.debug("Deleting records");
Connection conn = null;
fileDir = getAttachmentDirectoryForNewAttachments(tableId, key);
try {
conn = this.getTransactionConnection();
final String inpName = "inpname";
String strName = "";
final FileItem file = vars.getMultiFile(inpName);
if (file == null)
throw new ServletException("Empty file");
strName = file.getName();
// FIXME: Get the directory separator from Java runtime
int i = strName.lastIndexOf("\\");
if (i != -1) {
strName = strName.substring(i + 1);
// FIXME: Get the directory separator from Java runtime
} else if ((i = strName.lastIndexOf("/")) != -1) {
strName = strName.substring(i + 1);
}
boolean fileExists = false;
final TabAttachmentsData[] files = TabAttachmentsData.select(this, "'" + vars.getClient()
+ "'", "'" + documentOrganization + "'", tableId, key);
for (TabAttachmentsData data : files) {
if (data.name.equals(strName)) {
fileExists = true;
cFileId = data.cFileId;
}
}
if (!fileExists) {
path = getPath(fileDir);
// We only insert a new record if there is no record for this file
TabAttachmentsData.insert(conn, this, cFileId, vars.getClient(), documentOrganization,
vars.getUser(), tableId, key, strDataType, strText, strName, path);
} else {
// We update the existing record
TabAttachmentsData.update(this, vars.getUser(), strDataType, strText, cFileId);
}
try {
// FIXME: Get the directory separator from Java runtime
final File uploadedDir = new File(globalParameters.strFTPDirectory + "/" + fileDir);
if (!uploadedDir.exists())
uploadedDir.mkdirs();
final File uploadedFile = new File(uploadedDir, strName);
file.write(uploadedFile);
// FIXME: We should be closing the file here to make sure that
// is closed
// and that is does not really get closed when the GC claims the
// object (indeterministic)
} catch (final Exception ex) {
throw new ServletException(ex);
}
releaseCommitConnection(conn);
} catch (final Exception e) {
try {
releaseRollbackConnection(conn);
} catch (final Exception ignored) {
}
e.printStackTrace();
log4j.error("Rollback in transaction");
myMessage.setType("Error");
myMessage.setMessage(Utility.messageBD(this, "ProcessRunError", vars.getLanguage()));
return myMessage;
// return "ProcessRunError";
}
myMessage.setType("Success");
myMessage.setMessage(Utility.messageBD(this, "Success", vars.getLanguage()));
return myMessage;
// return "";
}
示例15: uploadFile2Folder
import org.apache.commons.fileupload.FileItem; //导入方法依赖的package包/类
/**
* 将上传的文件放到指定的目录下
* @param request HttpServletRequest对象
* @param sourceFolder 指定文件夹
* @param fileName 指定文件名,包含扩展名(数组)
* @return List 返回文件名集合
* @throws Exception 抛出异常
*/
public List uploadFile2Folder(HttpServletRequest request,String sourceFolder,String[] fileName)throws Exception{
DiskFileItemFactory factory = new DiskFileItemFactory();
if(sizeThreshold!=0){
factory.setSizeThreshold(sizeThreshold);
}
if(repositoryPath!=null){
factory.setRepository(new File(repositoryPath));
}
ServletFileUpload upload = new ServletFileUpload(factory);
if(sourceFolder==null){
sourceFolder="";
}
if(sizeMax!=0){
upload.setSizeMax(sizeMax);
}
if(encoding!=null){
upload.setHeaderEncoding(encoding);
}
//若指定文件加不存在,则创建
List list = new ArrayList();
File file=new File(sourceFolder);
if(!file.exists()){
file.mkdir();
}
//开始读取上传信息
List fileItems = upload.parseRequest(request);
if(fileItems!=null&&fileItems.size()!=0){
Iterator it=fileItems.iterator();
int i=0;
while(it.hasNext()){
FileItem fi=(FileItem)it.next();
if(!fi.isFormField()){
//忽略其他不是文档域的任何表单信息
String name=fi.getName();
String nameDir=name;
if(name.lastIndexOf("\\")>=0){
nameDir=name.substring(name.lastIndexOf("\\"));
}
String type=null;
if(nameDir.lastIndexOf(".")>=0){
type=nameDir.substring(nameDir.lastIndexOf(".")+1);
}
//自己指定文件名
if(fileName!=null){
if(fileName[i]!=null){
nameDir=fileName[i];
}
i++;
}
//判断是否设定了上传的文件类型
if(type!=null&&!isHave(types,type)){
File f=new File(sourceFolder+nameDir);
fi.write(f);
list.add(sourceFolder+nameDir);
}
}
}
}
return list;
}