上传文件

[color=red]Action:[/color]




/**
* 上传
* @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");
}




[color=red]ActionForm:[/color]


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>
上传数据文件>><br>
 <input type="file" name="files" />
 <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>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值