上传文件

Action:



/**
	 * 上传
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */

	public ActionForward uploadFile(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {

		String encoding = request.getCharacterEncoding();
		if ((encoding != null) && (encoding.equalsIgnoreCase("utf-8"))) {
			response.setContentType("text/html; charset=gb2312");
			//如果没有指定编码,编码格式为gb2312
		}
		NSRInfoImportForm theForm = (NSRInfoImportForm) form;
		FormFile file = theForm.getFiles();
		//取得上传的文件

		OutputStream bos = null;
		InputStream stream = null;
		try {
			stream = file.getInputStream();

			//得到目标目录的绝对路径
			String filePath = request.getRealPath("/nsrinfo/upload");//上传到指定的upload包中 
			
			File file1=new File(filePath);
			deleteDirectory(file1 );//删除上传目录
			if (!file1.exists()) {
				file1.mkdir();
			}
			File targetpath = new File(filePath + "/" + file.getFileName());
			if (!targetpath.exists()) {
				targetpath.createNewFile();
			}
			//上传到指定的upload包中
			bos = new FileOutputStream(targetpath);

			//建立一个上传文件的输出流
			//System.out.println(filePath+"/"+file.getFileName());
			int bytesRead = 0;
			byte[] buffer = new byte[8192];
			while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {

				bos.write(buffer, 0, bytesRead);//将文件写入服务器

			}

		} catch (Exception e) {
			System.err.print(e);
		} finally {
			try {
				bos.close();
				stream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}

		}

		return mapping.findForward("nsrinfo/import_main");
	}




ActionForm:

package com.infosys.struts.form;

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

public class NSRInfoImportForm extends ActionForm {
	
	protected FormFile files;

	public FormFile getFiles() {
		return files;
	}

	public void setFiles(FormFile files) {
		this.files = files;
	}
}





jsp:
<form  name="form1" method="post" enctype="multipart/form-data"> 
  <table width="95%" border="0" cellspacing="0" cellpadding="0" align="center">
	     <tr height="28" align="left">   
	     <td>
	       上传数据文件&gt;&gt;<br>
	       &nbsp;<input type="file" name="files" />
	       &nbsp;<input type="button" name="b1"   value="上传" onclick="upload();"/>
	       
	      </td>
	      
	      <td align="right">
	      <br>
  <tr>
  </table>

 <script type="text/javascript">
 function upload(){
   form1.action="import.do";
   form1.submit();
 }

</script>

</form>

你可能感兴趣的:(apache,html,jsp,struts)