使用ssh上传文件

来源:互联网 发布:淘宝拍摄布光 编辑:程序博客网 时间:2024/04/30 00:30

1.在upload.jsp页面中,亮黄色的是重点

<div class="pageContent">
<form method="post" enctype="multipart/form-data" action="doAdd" class="pageForm required-validate" onsubmit="return iframeCallback(this, dialogAjaxDone);">
<div class="pageFormContent" layoutH="56">
<p style="width: 980px;">
<label>标题:</label> <input type="text" size="30" name="noticeTitle"/>
</p>
<p style="width: 980px;">
<label>图片或共享文件:</label> <input name="image" type="file" size="15"/>
</p>
<p style="width: 980px;">
<label>内容:</label>
<textarea name="noticeContent" id="editor" class="editor" name="description" rows="25" cols="100">
</textarea>
</p>

</div>
<div class="formBar">
<ul>
<!--<li><a class="buttonActive" href="javascript:;"><span>保存</span></a></li>-->
<li><div class="buttonActive"><div class="buttonContent"><button type="submit">保存</button></div></div></li>
<li>
<div class="button"><div class="buttonContent"><button type="button" class="close">取消</button></div></div>
</li>
</ul>
</div>
</form>
</div>

2.在struts.xml中

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
    <!-- 做添加功能时图片的上传 -->
    <!-- 指定允许上传的文件最大字节数。默认值是2097152(2M) -->
    <constant name="struts.multipart.maxSize" value="10701096"/>
    <!-- 设置上传文件的临时文件夹,默认使用javax.servlet.context.tempdir -->
    <constant name="struts.multipart.saveDir " value="d:/tmp" />

    
    <package name="NOTICES" namespace="/" extends="json-default">  
  <!--添加保存  -->
  <action name="doAdd" class="showNotice" method="addSave">
  <result name="success" type="json"/>
  <result name="error" type="json"/>
 
  <!-- 图片的上传 -->
  <!-- 动态设置savePath的属性值 -->
            <param name="savePath">/upload</param>
            <result name="success" type="json">
            <param name="contentType">text/html</param>
            </result>
            <!-- 拦截器 -->
            <interceptor-ref name="fileUpload">
                <!-- 文件过滤 -->
                <!-- <param name="allowedTypes">image/bmp,image/png,image/gif,image/jpeg</param>  -->               
                <!-- 文件大小, 以字节为单位 -->
               <!--  <param name="maximumSize">10025956</param> -->
            </interceptor-ref>
            <!-- 默认拦截器必须放在fileUpload之后,否则无效 -->
            <interceptor-ref name="defaultStack" />

  </action>
    </package>
</struts>

3.在UploadHelper.java中

package noticeCOMMON;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;


import org.apache.struts2.ServletActionContext;


import com.opensymphony.xwork2.ActionSupport;


@SuppressWarnings("serial")
public class UploadHelper extends ActionSupport {


    // 封装上传文件域的属性
    private File image;
    // 封装上传文件类型的属性
    private String imageContentType;
    // 封装上传文件名的属性
    private String imageFileName;
    // 接受依赖注入的属性
    private String savePath;


    
public String startUpFile() {
        FileOutputStream fos = null;
        FileInputStream fis = null;
        try {
            // 建立文件输出流
            System.out.println(getSavePath());
            fos = new FileOutputStream(getSavePath() + "\\" + getImageFileName());
            // 建立文件上传流
            fis = new FileInputStream(getImage());
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = fis.read(buffer)) > 0) {
                fos.write(buffer, 0, len);
            }
        } catch (Exception e) {
            System.out.println("文件上传失败");
            e.printStackTrace();
        } finally {
            close(fos, fis);
        }
        return SUCCESS;
    }


    /**
     * 返回上传文件的保存位置
     * 
     * @return
     */
    public String getSavePath() throws Exception{
        return ServletActionContext.getServletContext().getRealPath(savePath); 
    }


    public void setSavePath(String savePath) {
        this.savePath = savePath;
    }


    public File getImage() {
        return image;
    }


    public void setImage(File image) {
        this.image = image;
    }


    public String getImageContentType() {
        return imageContentType;
    }


    public void setImageContentType(String imageContentType) {
        this.imageContentType = imageContentType;
    }


    public String getImageFileName() {
        return imageFileName;
    }


    public void setImageFileName(String imageFileName) {
        this.imageFileName = imageFileName;
    }


    private void close(FileOutputStream fos, FileInputStream fis) {
        if (fis != null) {
            try {
                fis.close();
            } catch (IOException e) {
                System.out.println("FileInputStream关闭失败");
                e.printStackTrace();
            }
        }
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException e) {
                System.out.println("FileOutputStream关闭失败");
                e.printStackTrace();
            }
        }
    }


}

4.在实体类中继承UploadHelper.java

5.在applicationContext.xml中

<?xml version="1.0" encoding="UTF-8"?>
<beans


xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"  
xmlns:mvc="http://www.springframework.org/schema/mvc"  
xsi:schemaLocation="http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
http://www.springframework.org/schema/tx 
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<!-- 通知 -->
<bean id="noticeDAOImpl" class="noticeDAOIMPL.noticeDAOImpl"></bean>
<bean id="showNotice" class="noticeSERVICE.noticeService" scope="prototype">
<property name="notice" ref="noticeDAOImpl"></property>
</bean>
</beans>

6.在noticeService.java类中的addSave方法中

// 添加保存
public String addSave() throws Exception {
Notices m = new Notices();
m.setNoticeTitle(getNoticeTitle());
m.setNoticeContent(getNoticeContent());
String finename=getImageFileName().toLowerCase();
String exsString=finename.substring(finename.lastIndexOf(".")+1);
if (exsString.equals("bpm")||exsString.equals("png")||exsString.equals("gif")||exsString.equals("jpeg")||exsString.equals("jpg")) {
//图片
m.setNoticeImg(getImageFileName());
}else {
m.setNoticeFile(getImageFileName());
m.setNoticeImg("img");
}
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date dt=new Date();
m.setNoticeTime(sdf.format(dt));
dwzResult dr = new dwzResult();
dr.setMessage("操作成功");
int flag = notice.addNotice(dp, m);
if (flag > 0) {
// 图片上传时,调用Common类中的startUpFile()方法
startUpFile();

//文件上传
dr.setStatusCode("200");
// 使用JSONObject生成json
JSONObject json = JSONObject.fromObject(dr);
// 给了自定义的属性,在前台的DWZ框架中from表单中return iframeCallback(this,
// dialogAjaxDone)
setDwzJsonResult(json.toString());
return SUCCESS;
} else {
dr.setStatusCode("300");
JSONObject json = JSONObject.fromObject(dr);
setDwzJsonResult(json.toString());
return ERROR;
}
}

0 0
原创粉丝点击