现在的位置: 首页 > 综合 > 正文

Struts1.x实现上传

2018年07月13日 ⁄ 综合 ⁄ 共 2079字 ⁄ 字号 评论关闭

package com.demo.strutsupload;

import java.io.File;
import java.io.FileOutputStream;

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

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;

public class UploadAction extends Action
{
	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception
	{
		UploadForm uploadForm = (UploadForm) form;
		FormFile myFile = uploadForm.getMyfile();
		String dir = request.getSession().getServletContext().getRealPath("/") + "upload/images";
		if (myFile != null)
		{
			System.out.println(myFile.getFileName());
			File uploadFile = new File(dir);
			String path = uploadFile.getAbsolutePath();
			System.out.println("Path:" + path);
			if (!uploadFile.exists() || uploadFile == null)
			{
				uploadFile.mkdirs();
			}
			FileOutputStream fos = new FileOutputStream(path + "\\"
					+ myFile.getFileName());
			fos.write(myFile.getFileData());
			fos.flush();
			fos.close();
		}

		return mapping.findForward("success");
	}
}

package com.demo.strutsupload;

import org.apache.struts.action.ActionForm;
import org.apache.struts.upload.FormFile;

public class UploadForm extends ActionForm
{
	private String title;
	private FormFile myfile;

	public String getTitle()
	{
		return title;
	}

	public void setTitle(String title)
	{
		this.title = title;
	}

	public FormFile getMyfile()
	{
		return myfile;
	}

	public void setMyfile(FormFile myfile)
	{
		this.myfile = myfile;
	}
}

<%@ page language="java" contentType="text/html; charset=GBK"
    pageEncoding="GBK"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Upload File Test</title>
</head>
<body>
	<form action="upload.do" method="post" enctype="multipart/form-data">
		<table>
			<tr>
				<td>标题</td>
				<td><input type="text" name="title"></td>		
			</tr>
			<tr>
				<td>文件</td>
				<td><input type="file" name="myfile"></td>
			</tr>
			<tr>
				<td><input type="submit" value="提交"></td>
				<td><input type="reset" value="重置"></td>
			</tr>
		</table>
	</form>
</body>
</html>

抱歉!评论已关闭.