首页 > Web开发 > 详细

Struts文件上传

时间:2015-03-28 14:09:37      阅读:125      评论:0      收藏:0      [点我收藏+]

首先要加入上传文件需要的jar文件 commons-fileupload-1.2.1.jar commomons-io-1.3.2.jar不同版本的strutsjar文件的版本也可能不同,一般在配置struts的时候已经加载了这两个文件,

然后再页面创建文件上传表单

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP ‘FileUpload.jsp‘ starting page</title>
<style type="text/css">
.mylabel{
height:33px;
width: 142px;
display: block;
overflow: hidden;
background: url(image/huang_1_btn.jpg);
}
.file{
display:none;
}
#show{
width : 600px;
height: 50px;
background-color:#efef00;
font-size: 21px;
color:#00f;
font-weight: bold;
line-height: 50px;
text-align: center;
overflow: hidden;
}
#sub{
display : block;
width : 142px;
height: 33px;
background-color:#e34545;
margin-top:10px;
line-height: 33px;
text-decoration: none;
color : #fff;
}
</style>
<script type="text/javascript">
function show(value){
var $show = document.getElementById("show");
$show.innerHTML= value;
var image = document.getElementById("image");
image.src = value;
}
function sub(){
var fo = document.getElementById("form1");
fo.submit();
}
</script>
</head>

<body>
<center>
<form id="form1" action="http://localhost:8080/Struts/fileup/demo1.action" method="POST" enctype="multipart/form-data">
<label class="mylabel">
<input type="file" name="image" class="file" onchange="show(this.value);"/>
</label>
</form>
<div id="show">

</div>
<a href="javascript:sub()" id="sub">上传文件</a>
</center>
</body>
</html>

 

里面用到的一些图片可以自行替代

技术分享

 

现在可以编写action 了

package com.fileupload;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;

public class demo1 {

private File image;                     //必须与文件上传表单中的 file 的 name属性一样
private String imageFileName;    //必须是上面的文件名+FileName

public File getImage() {
return image;
}
public void setImage(File image) {
this.image = image;
}
public String getImageFileName() {
return imageFileName;
}
public void setImageFileName(String imageFileName) {
this.imageFileName = imageFileName;
}

public String execute() throws IOException{
String realpath = ServletActionContext.getServletContext().getRealPath("/image"); //获得image的绝对路径
System.out.println(realpath);
File saveFile = new File(new File(realpath),imageFileName);   //在image文件夹下创建同名文件
FileUtils.copyFile(image, saveFile);   //将上传的文件复制给创建的同名文件
return "success";
}
}

 

Struts文件上传

原文:http://www.cnblogs.com/dbqjava/p/4374069.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!