struts2 上传和下载

本文介绍了一个基于JSP的图片上传与下载功能实现案例,包括前端表单设计、JavaScript验证、后端处理流程及文件读写操作。通过具体代码展示了如何确保文件格式正确并限制文件大小,同时实现了上传后的图片保存及后续下载功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

jsp:

<form action="" method="post" enctype="multipart/form-data" id="uploadPicForm">
        <input type="hidden" name="ids" id="orderids">
        <table class="input" style="margin-left: auto; margin-right: auto; margin-top: 5px; width: 98%;">
                <tbody>
                    <tr>
                        <th width="105px;">上传峰图</th>
                        <td><input type="file" name="upload" id="uploadPic" accept=".gif,.jpg,.jpeg,.png,.amp"></td>
                    </tr>
                </tbody>
            </table>
         <p class="buttonContainer">
                 <a href="javascript:void(0);" class="easyui-linkbutton"  data-options="iconCls:'icon-save'" onclick="uploadPic()" style="margin-left:8px">上传</a>
                <a href="javascript:void(0);" class="easyui-linkbutton"  data-options="iconCls:'icon-cancel'" onclick="closeUploadPicDialog()" style="margin-left:8px">关闭</a>
            </p>
    </form>

js:

//上传峰图点击上传
    function uploadPic(){
        if($("#uploadPic").val()==''){
            $.messager.alert("系统提示信息","请选择要上传的峰图文件!","info");
            return;
        }
        var suffix=$("#uploadPic").val().substring($("#uploadPic").val().lastIndexOf(".")).toLowerCase();
        if(!/^\.(gif|jpg|jpeg|png|amp)$/.test(suffix)){
            $.messager.alert("系统提示信息","请选择正确的峰图文件!","info");
            return false;
        }
        $.messager.progress({title:"系统提示信息",msg:"操作中..."});
        $('#uploadPicForm').form('submit', {
            url:base + "/two-check/validate-order-mutation_att/uploadPic.action?t="+ new Date().getTime(),
               success:function(data){
                   $.messager.progress("close");
                   var msg = eval('(' + data + ')');  
                if(!msg.statusCode && msg.statusCode!=0){
                    return;
                }
                if(msg.statusCode == 2){
                    $("#uploadPicDialog").dialog("close");
                    $("#mutationVerify").datagrid("reload");
                }else if(msg.statusCode == 5){
                    $.messager.alert("系统提示信息","上传文件大小不能超过10M!","info");
                }else{
                    $.messager.alert("系统提示信息","上传失败!","info");
                }
               },
               error:function() {
                   $.messager.progress("close");
                $.messager.alert("系统提示信息","执行操作时发生错误!","error");
               }
        });
    }
    //下载峰图
      function downPic(id,e){
        e.stopPropagation();
        e.preventDefault();
        window.location.href = base + "/two-check/validate-order-mutation/downPic.action?id="+id+"&t=" + new Date().getTime();
      }


action:

 

/**上传使用*/
    private File upload; // 得到上传的文件,此属性对应于表单中文件字段的名称
    /**上传文件名*/
    private String uploadFileName;

set、get 方法省略

public String uploadPic(){
        try {
            if(upload!=null && upload.length()>0){
                if(upload.length()>10485760){ //一次上传文件总大小不能超过10M
                    statusCode=5;
                }else{
                    mutationService.uploadPic(ids,upload,uploadFileName);
                    mutationService.updateIsExistMutation(ids);//如果上次成功,则更新工单对应的封图是否存在
                    statusCode=2;
                }
            }
        } catch (RuntimeException e) {
            e.printStackTrace();
            throw e;
        }
       return SUCCESS;
    }

service:

public void uploadPic(String ids, File upload, String uploadFileName) {
        int indexOf = uploadFileName.indexOf(".");
        String substring = uploadFileName.substring(indexOf);
        Integer type=1; //突变验证工单的类型为1
        String[] idStr = ids.split(",");
        if(idStr!=null && idStr.length>0){
            for (int i = 0; i < idStr.length; i++) {
                File file2 = new File(ReadPropertiesUtils.readProperties("path.properties","LAB_ORDER_PIC").concat(i+substring));
                try {
                    FileUtils.copyFile(upload,file2);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                Pic p=picDao.selectByOrderIdAndType(Integer.parseInt(idStr[i]),type);
                if(p!=null){
                    //先删除旧文件
                    File file=new File(ReadPropertiesUtils.readProperties("path.properties","LAB_ORDER_PIC")+p.getpName());
                    if(file.exists()){
                        file.delete();
                    }
                    //更新峰图记录
                    p.setName(uploadFileName);
                    p.setpName(FileUploadUtils.fileUploadReturnName(file2, "path.properties", "LAB_ORDER_PIC"));
                    picDao.update(p);
                }else{
                    Pic pic=new Pic();
                    pic.setOrderId(Integer.parseInt(idStr[i]));
                    pic.setName(uploadFileName);
                    pic.setpName(FileUploadUtils.fileUploadReturnName(file2, "path.properties", "LAB_ORDER_PIC"));
                    pic.setType(type);
                    picDao.insert(pic);
                }
            }
        }
    }

读取properties文件方法:

public class ReadPropertiesUtils {
    /**
     * 读取配置文件下的字段值
     * @param propertiesFile 配置文件包含路径
     * @param name 字段名称
     * @return 返回该字段值
     */
    public static String readProperties(String propertiesFile,String name){
        InputStream in=ReadPropertiesUtils.class.getClassLoader().getResourceAsStream(propertiesFile);
        Properties prop=new Properties();
        try {
            prop.load(in);
        } catch (IOException e) {
            throw new ExceptionInInitializerError("初始化配置文件失败");
        }
        return prop.getProperty(name);
    }
}

-----------------------------------------------------------------------------------------------------------------------------

下载:

action:

 public String downPic() throws Exception{
        try {
            Pic pic=mutationService.findPic(id);
            if(null != pic){
                String filename=pic.getName();
                if(null != filename && !"".equals(filename)){
                    filename=new String(filename.getBytes("gbk"), "iso-8859-1");
                    //获取文件路径,从而获取输入流
                    inputStream=new FileInputStream(new File(ReadPropertiesUtils.readProperties("path.properties","LAB_ORDER_PIC")+pic.getpName()));
                    HttpServletRequest req=ServletActionContext.getRequest();
                    req.setAttribute("filename", filename);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
        return SUCCESS;
    }

xml配置文件:

<action name="downPic" class="com.deyidf.lab.action.order.MutationSearchAction" method="downPic">
            <result type="stream">
                <param name="inputName">inputStream</param>
                <param name="ContentDisposition">attachment;filename=${#request.filename}</param>
                <param name="bufferSize">1024</param>
            </result>
        </action>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值