本文整理匯總了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;
}