`
dickyzhu
  • 浏览: 111758 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
文章分类
社区版块
存档分类
最新评论

UploadFile

阅读更多
You can upload files from your PC to the Wiki server. Use the Upload a File link in the left menu to get started. You can reference uploaded files with the simple form of the Markup link. For example, if we upload "ProjectPlan.doc" we can create a link like [ProjectPlan.doc].
The Wiki removes all punctuation and spaces from the fileid, so My Project-01.ppt will be stored as MyProject01.ppt.

Uploaded files go into the same NameSpace as the page from which Upload A File is launched.

文件上传参考:http://commons.apache.org/fileupload/

/**
 * @author William Horan
 * @version 1.0 October 5th 2007
 * UploadReferralAttachment.java
 * Documentation on the wiki at http://cct:9454/UploadReferralAttachment
 * Servlet for uploading multiple files to the Server/DataBase for referral attachment storage
 */

package com.metlife.metcare.core.attachment.servlet;

import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;

import com.chordiant.core.log.LogHelper;
import com.chordiant.service.clientagent.ClientAgentHelper;
import com.metlife.metcare.core.attachment.bean.FileBean;
import com.metlife.metcare.core.caseobjects.clientAgents.SaveCaseClientAgent;
import com.metlife.metcare.core.utility.SSString;

public class UploadReferralAttachment extends HttpServlet
{
	String PACKAGE_NAME = "com.metlife.metcare.core.upload.service";
	String CLASS_NAME = "UploadReferralAttachment";
	int maxsize = 2000048; // 1 mb
	int totalsize = 2000048; // 5mb

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		// Not handling Get, service must be invoked via Post.
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		String METHOD_NAME = "doPost";
		LogHelper.debug(PACKAGE_NAME, CLASS_NAME, METHOD_NAME, "Made it to the servlet");
		String reply = upload(request);
        //response.setHeader("Content-Type", "text/xml");
        //response.getWriter().write(reply);
        //response.getWriter().flush();
        request.setAttribute("id", reply);
        
        getServletConfig().getServletContext().getRequestDispatcher("/xAdvisorWeb/bundles/upload/doneattachfile.jsp").forward(request, response);
	}

	private String upload(HttpServletRequest request)
	{
		String METHOD_NAME = "upload";
        String reply = "";
		LogHelper.debug(PACKAGE_NAME, CLASS_NAME, METHOD_NAME, "Inside upload");
		try
		{

			int maxsize = 0;
			//Check that we have a file upload request
			//boolean isMultipart = ServletFileUpload.isMultipartContent(request);

			LogHelper.debug(PACKAGE_NAME, CLASS_NAME, METHOD_NAME, "Past MultiPart");

			//Create a factory for disk-based file items
			DiskFileItemFactory factory = new DiskFileItemFactory();

			LogHelper.debug(PACKAGE_NAME, CLASS_NAME, METHOD_NAME, "Done instantiation of DiskFile");
			/* All at once if needed
			//Create a factory for disk-based file items
			DiskFileItemFactory factory = new DiskFileItemFactory(yourMaxMemorySize, yourTempDirectory);
			*/

			//Set factory constraints
			factory.setSizeThreshold(maxsize);
			//factory.setRepository(repository);

			LogHelper.debug(PACKAGE_NAME, CLASS_NAME, METHOD_NAME, "Done setting factory constraints");

			//Create a new file upload handler
			ServletFileUpload upload = new ServletFileUpload(factory);

			LogHelper.debug(PACKAGE_NAME, CLASS_NAME, METHOD_NAME, "Done creating Handler for upload");

			//Set overall request size constraint
			upload.setSizeMax(totalsize);

			LogHelper.debug(PACKAGE_NAME, CLASS_NAME, METHOD_NAME, "done setting max size of upload request");

			//Parse the request
			List items = upload.parseRequest(request);

			LogHelper.debug(PACKAGE_NAME, CLASS_NAME, METHOD_NAME, "Done parsing should have a good list now.");

			//Process the uploaded items
			Iterator iter = items.iterator();
            Object fileObj = new Object();
			String description = "";
            String username = "";
            String authToken = "";
            String caseArchiveDate = "";
            String time = "";
			while (iter.hasNext())
			{
                FileItem item = (FileItem) iter.next();
                
				if (item.isFormField())
				{
                    LogHelper.debug(PACKAGE_NAME, CLASS_NAME, METHOD_NAME, "Processing a form field");
					String name = item.getFieldName();
					String value = item.getString();
                    LogHelper.debug(PACKAGE_NAME, CLASS_NAME, METHOD_NAME, "Name:" + name + " Value:" + value);
					if (name.equalsIgnoreCase("description"))
					{
						description = value;
					}
                    else if(name.equalsIgnoreCase("username"))
                    {
                        username = value;
                    }
                    else if(name.equalsIgnoreCase("auth"))
                    {
                        authToken = value;
                    }
					else if(name.equalsIgnoreCase("caseArchiveDate"))
					{
						caseArchiveDate = value;
					}
                    else if (name.equalsIgnoreCase("time"))
                    {
                        time = value;
                    }
				} else
				{
                    LogHelper.debug(PACKAGE_NAME, CLASS_NAME, METHOD_NAME, "Processing a file.");
                    fileObj = item;
				}
			}
            reply = processUploadedFile((FileItem) fileObj, description, username, authToken, caseArchiveDate);
            reply = reply + "|" + caseArchiveDate + "|" + time;

		} catch (FileUploadException e)
		{

			LogHelper.error(PACKAGE_NAME, CLASS_NAME, METHOD_NAME, "There was a problem processing the upload request Exception:" + e.toString());
            reply = "There was a problem processing the upload request Exception:" + e.toString();
		}
        
		return reply;
	}
	private String processUploadedFile(FileItem item, String description, String userName, String authToken, String caseArchiveDate)
	{
		String METHOD_NAME = "processUploadedFile";
		LogHelper.debug(PACKAGE_NAME, CLASS_NAME, METHOD_NAME, "Processing an uploaded file");
		String reply = "";
        // Process a file upload
		if (!item.isFormField() && !SSString.isEmpty(item.getName()))
		{
			reply = doUpload(item, description, userName, authToken, caseArchiveDate);
		}
        return reply;
	}
	private String doUpload(FileItem item, String description, String userName, String authToken, String caseArchiveDate)
	{

		String METHOD_NAME = "doUpload";
		LogHelper.debug(PACKAGE_NAME, CLASS_NAME, METHOD_NAME, "Starting upload sewquence");
		FileBean fBean = new FileBean();
        String reply = "Unable to Call SaveImage";
		try
		{

			String fieldName = item.getFieldName();
			String fileName = item.getName();
			String contentType = item.getContentType();
			boolean isInMemory = item.isInMemory();
			long sizeInBytes = item.getSize();

			fileName = FilenameUtils.getName(fileName);

            
			fBean.setBytes(item.get());
			fBean.setDescription(description);
			fBean.setFileName(fileName);
            fBean.setAuthToken(authToken);
            fBean.setUserName(userName);
            fBean.setOtherId("File");
            fBean.setCaseArchiveDate(caseArchiveDate);

			if ((SSString.isEmpty(userName)) || (SSString.isEmpty(authToken))) {
				LogHelper.error(PACKAGE_NAME, CLASS_NAME, "doImageUpload", "userName and/or AuthToken empty");
			} else {
				try {
					SaveCaseClientAgent saveCaseClientAgent = (SaveCaseClientAgent) ClientAgentHelper.getClientAgent(SaveCaseClientAgent.CLASS_NAME);
					reply = saveCaseClientAgent.saveReferralImage(userName, authToken, fBean);
				} catch (Exception e) {
					LogHelper.error(PACKAGE_NAME, CLASS_NAME, "doImageUpload", "exception: " + e.toString());
				}
			}

			//SaveReferralAttachment savereferral = new SaveReferralAttachment();

			//reply = savereferral.saveAttachment(fBean);



			//Whoran Commented out was only used for poc and writing file to server file system. 
			/*
			    //Strip full path and get just the name
			    if (fileName != null)
			    {
			            
			        LogHelper.error(PACKAGE_NAME, CLASS_NAME, METHOD_NAME, "Uploading File: " + FilenameUtils.getName(fileName) + " Size : " + sizeInBytes);
			        fileName = FilenameUtils.getName(fileName);
			    }
			        
			    LogHelper.error(PACKAGE_NAME, CLASS_NAME, METHOD_NAME, "done pulling file properties");
			        
			        
			            
			    // Process a file upload
			    if (writeToFile)
			    {
			        LogHelper.error(PACKAGE_NAME, CLASS_NAME, METHOD_NAME, "Writing");
			        //File uploadedFile = new File("C:\\test\\" + fileName);
			        LogHelper.error(PACKAGE_NAME, CLASS_NAME, METHOD_NAME, "done creating");
			        //item.write(uploadedFile);
			        LogHelper.error(PACKAGE_NAME, CLASS_NAME, METHOD_NAME, "done writing");
			    } else
			    {
			        //InputStream uploadedStream = item.getInputStream();
			        //uploadedStream.close();
			
			    }
			*/

		} catch (Exception e)
		{

			LogHelper.error(PACKAGE_NAME, CLASS_NAME, METHOD_NAME, "There was a problem uploading the file Exception:" + e.toString());
		}
        

        return reply;
	}

	//Whoran Commented out as I believe class variables are not thread safe.
	/*
	private String processFormField(FileItem item)
	{
	
	// Process a regular form field
	if (item.isFormField())
	{
	    String name = item.getFieldName();
	    String value = item.getString();
	    if(name.equalsIgnoreCase("referralID"))
	    {
	        value = ReferralID
	    }
	}
	
	}
	*/
}

分享到:
评论

相关推荐

    uploadFile

    在Android开发中,"uploadFile"是一个常见的任务,特别是对于涉及到用户交互的应用,例如社交、文件分享或云端存储服务。这个实例,"上传文件demo,android上传图片实例",是关于如何在Android应用中实现从设备相册...

    UpLoadFile

    本文将重点解析标题为"UpLoadFile"的项目,它是基于之前"UpLoadDemo"的改版,意味着它在文件上传功能上进行了优化和增强。 在"UpLoadDemo"的基础上,"UpLoadFile"可能包含了更完善的文件上传功能。在ASP.NET中,...

    微信小程序调用uploadFile向七牛云存储上传图片

    本篇文章将详细探讨如何利用微信小程序的`uploadFile`接口来实现向七牛云存储上传图片的功能。 首先,我们需要了解七牛云存储。七牛云是一家提供云存储和CDN加速服务的公司,它提供了丰富的API和SDK,使得开发者...

    uploadfile

    "uploadfile"这个标题可能指的是一个文件上传功能,特别是与图片上传相关的操作。在这个场景下,"大小图片的转换"是核心知识点,意味着我们需要讨论如何处理不同尺寸的图片,包括缩小大图和放大小图。 图片的大小...

    Uploadfile 多文件上传

    "Uploadfile"这个标签可能指的是一个特定的文件上传库或者组件,它专门处理用户在Web端选择并上传多个文件的需求。在本场景中,"Uploadfile.dll"可能是这个库的动态链接库文件,用于提供文件上传的相关服务。 多...

    js jquery无刷新上传插件及实现源码 两种uploadFile 和Uploadify

    本文将深入探讨两种常用的无刷新上传插件:`uploadFile`和`Uploadify`,并结合AJAX上传图片的实例`FileUpload`来详细解析其工作原理和实现方式。 首先,我们来看`uploadFile`插件。`uploadFile`是一个基于jQuery的...

    微信小程序 wx.request 和 wx.uploadFile请求/上传封装,JSEncrypt加密字符串超长采用分段加密

    综上所述,微信小程序的网络请求和文件上传都需要考虑数据安全,合理使用`wx.request`、`wx.uploadFile`结合`JSEncrypt`进行分段加密是保护用户数据的有效手段。同时,开发者还应关注其他安全最佳实践,以增强整体的...

    uploadFile控件上传文件,格式判断

    path = System.Web.HttpContext.Current.Server.MapPath("~/UploadFile//");//文件保存的路径 if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } #endregion } else { //超过了文件的...

    jsp_Uploadfile_2.rar_DEMO

    【标题】"jsp_Uploadfile_2.rar_DEMO" 是一个关于JSP文件上传功能的演示项目,其中可能包含了如何在Java服务器页面(JSP)上实现文件上传的实例代码和指南。JSP是Java EE平台的一部分,它允许开发者创建动态网页应用...

    UploadFile.class.php支持多文件上传的上传类

    $upload=new UploadFile(); if(!$upload->upload()) { // 上传错误提示错误信息 $this->error($upload->getErrorMsg()); }else{ // 上传成功 获取上传文件信息 $info = $upload->getUploadFileInfo(); }

    JAVA 使用uploadFile实现文件上传服务器

    `uploadFile`通常指的是客户端通过HTTP请求将文件发送到服务器的过程。本篇文章将详细介绍如何使用Java的`Apache Commons FileUpload`库来实现文件上传到服务器的功能。 Apache Commons FileUpload是一个用于处理...

    uploadfile(包含实例)

    "uploadfile(包含实例)"这个标题暗示了我们将会探讨一个关于文件上传的实际示例,而"JAVA上传"标签进一步确认了我们将专注于Java语言中的相关技术。在这个场景下,我们通常会使用Servlet、HTTP多部分请求(Multipart...

    android 上传文件(UpLoadFile)

    用于文件上传 参数 文件名 上传所用的 UpLoadFile 进程Dialog

    UpLoadFile MVC完整Demo支持断点续传

    【标题】"UpLoadFile MVC完整Demo支持断点续传" 涉及到的关键技术主要是文件上传和断点续传,在MVC框架下实现。MVC(Model-View-Controller)是微软提出的一种软件设计模式,常用于构建Web应用程序。在本Demo中,它...

    Ajax UpLoadFile 多个大文件上传控件 v1.15.rar

    Ajax UploadFile 多个大文件上传控件 v1.15 是一个专为ASP.NET平台设计的组件,它允许用户在网页上实现多文件大文件的异步上传功能。这个控件版本兼容ASP.NET 1.0和2.0框架,意味着它可以在较旧的系统环境中运行,...

    UploadFile.zip

    "UploadFile.zip" 提供了一个实现这一功能的资源包。在这个包中,我们可以找到相关的代码、配置和可能的示例,以帮助我们理解和实现JavaWeb中的文件上传。 首先,我们要理解文件上传的基本流程。当用户通过表单提交...

    springboot uploadFile

    在SpringBoot项目中实现文件上传功能是常见的需求,而"springboot uploadFile"的标题和描述表明我们要讨论的是如何在SpringBoot应用中实现文件上传。SpringBoot提供了便捷的方式与SpringMVC集成,后者是Spring框架的...

    jquery.uploadfile

    jquery.uploadfile插件3.1.10版本

Global site tag (gtag.js) - Google Analytics