首页 > 学院 > 开发设计 > 正文

Struts文件上传

2019-11-14 23:29:56
字体:
来源:转载
供稿:网友
Struts文件上传

首先要加入上传文件需要的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; //必须是上面的文件名+FileNamepublic 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";}}


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表