文件上传(JSP + Servlet)

一、JSP + Servlet 实现简单的文件上传:

1、使用的jar包:commmons-fileupload.jar

2、Jsp页面:enctype="multipart/form-data"

<%@page pageEncoding="UTF-8" contentType="text/html; charset=UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
	<base href="<%=basePath%>">
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
	<script type="text/javascript">
    	function validator(){
           var file = document.getElementById("file").value;
           if(file == null || file == ""){
                alert('请选择需要上传的文件');
                return false;
           }
           return true;
		}
	</script>
</head>
<body>
	<form method="post" name="upload" enctype="multipart/form-data" action="upload" onsubmit="return validator();">
		<input id="file" name="file" type="file" value="请选择上传文件"/>
		<input type="submit" value="上传" />
	</form>
</body>
</html>

2、Servlet实现:

public class Upload extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, 
            HttpServletResponse response) {
        String tempDirectory = "d:\\temp\\"; // 临时文件夹:上传成功之前存放缓存的位置
        String fileDirectory = "d:\\uploadFiles\\"; // 文件存放目录
        try {
            // 将未完全上传成功的信息放到指定的临时文件夹
            File repositoryFile = new File(tempDirectory);
            int sizeThreshold = 1024 * 64; // 写满该大小的缓存后,存入硬盘中。
            FileItemFactory factory = new DiskFileItemFactory(sizeThreshold,  
                    repositoryFile);
            ServletFileUpload upload = new ServletFileUpload(factory);
            upload.setSizeMax(500*1024*1024); //set every upload file size <500Mb
            List items = upload.parseRequest(request); // 这里开始执行上传
            Iterator iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                File uploadedFile = new File(fileDirectory + item.getName());
                item.write(uploadedFile);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

3、web.xml配置:

<servlet>
	<servlet-name>fileUpload</servlet-name>
	<servlet-class>test.Upload</servlet-class>
</servlet>
<servlet-mapping>
	<servlet-name>fileUpload</servlet-name>
	<url-pattern>/upload</url-pattern>
</servlet-mapping>

 

==================================================================================================

 

二、JSP + Struts1实现文件上传:

1、Form表单:

 

public class UploadFileForm extends ActionForm{
	FormFile uploadFile;
	public FormFile getUploadFile() {
		return uploadFile;
	}
	public void setFormFile(FormFile uploadFile) {
		this.uploadFile = uploadFile;
	}
}

2、 Action:

 

public class UploadAction extends Action{
	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		UploadFileForm uploadFileForm = (UploadFileForm) form;
		FormFile file = uploadFileForm.getUploadFile();
		String fileName = file.getFileName();
		InputStream is = file.getInputStream();
		OutputStream os = new FileOutputStream("D:\\" + fileName);
		while (is.read() != -1) {
			os.write(is.read());
		}
		return super.execute(mapping, form, request, response);
	}
}

3、Jsp:file的name属性与Form表单中FormFile名称对应。

4、web.xml:ActionServelet的配置

5、struts-config.xml:action配置

 

==================================================================================================


三、JSP + Struts2实现文件上传

Action实现:

 

public class UploadAction extends ActionSupport {
	private File upload;
	private String uploadFileName;

	public File getUpload() {
		return upload;
	}

	public void setUpload(File upload) {
		this.upload = upload;
	}

	public String getUploadFileName() {
		return uploadFileName;
	}

	public void setUploadFileName(String uploadFileName) {
		this.uploadFileName = uploadFileName;
	}

	public String upload() throws IOException {
		InputStream is = new FileInputStream(upload);
		OutputStream os = new FileOutputStream("D:\\" + uploadFileName);
		while (is.read() != -1) {
			os.write(is.read());
		}
	}
}

          

        关于文件上传中文乱码的问题:Struts从request里利用BeanUtils.populate()把值赋给form的时候已经是乱码的,所以赋值之前要进行编码的转换。可以通过写过滤器进行编码的设置。

 

 

 

 

 

你可能感兴趣的:(文件上传)