spirngMVC文件上传例子

本文介绍了一个文件上传功能的具体实现过程,包括表单控件设计、AJAX上传处理、服务器端文件接收及配置等关键技术细节。

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

1.上传用到的一些表单控件,如下所示:

    <div class="std_photo">                                 
        请上传图片:<img id="pictureImage1" name="pictureImage1"  src="${userDto.pictureImage}"  height="200" width="100"  />  
                    <input type="hidden" id="pictureImage"  name="pictureImage" value="">   
                    <input id="file" type="file" name="file" />   
                    <input type="button" value="保存"   class="btn" />  
                    
    </div>  

其中 类型type为hidden的控件为一个隐藏域,它专门用来用userDto里面的pictureImage交互的。而img图片控件同userDto.pictureImage绑定起来。 通过点击保存响应一个ajax事件.


2.ajax响应事件,如下所示:

    function ajaxFileUpload() {  
                  
                $.ajaxFileUpload({  
                        url : 'FileUploadForm.do?method=uploadAjax', // 需要链接到服务器地址  
                        secureuri : false,  
                        fileElementId : 'file', // 文件选择框的id属性  
                        dataType : 'json', // 服务器返回的格式,可以是json  
                        success : function(data, status) // 相当于java中try语句块的用法  
                        {  
                                  
                                //alert("成功: " + data.path);  
                                $("#pictureImage1")[0].src = data.path;  
                                $("#pictureImage").val(data.path);  
                                  
                        },  
                        error : function(data, status, e) // 相当于java中catch语句块的用法  
                        {  
                                alert("失败");  
                        }  
                });  
        }  

注意:这个ajax事件用到了一个JS文件,为:

<script type="text/javascript" src="${contextPath}/js/base/user/ajaxfileupload.js"></script>
这个要在jsp文件头上面进行申明,才可以使用。


3.ajax文件中使用到的文件上传控制器,如下所示:

    /* 
        * Copyright (C) 2012 GZ-ISCAS Inc., All Rights Reserved. 
        */  
        package cn.ac.iscas.gz.nssc.base.web.user;  
        import java.io.File;  
        import java.io.FileOutputStream;  
        import java.io.IOException;  
        import java.util.HashMap;  
        import java.util.Map;  
        import javax.servlet.http.HttpServletRequest;  
        import javax.servlet.http.HttpServletResponse;  
        import net.sf.json.JSONObject;  
        import org.springframework.stereotype.Controller;  
        import org.springframework.ui.ModelMap;  
        import org.springframework.util.FileCopyUtils;  
        import org.springframework.validation.BindingResult;  
        import org.springframework.web.bind.annotation.ModelAttribute;  
        import org.springframework.web.bind.annotation.RequestMapping;  
        import org.springframework.web.bind.annotation.RequestMethod;  
        import org.springframework.web.bind.annotation.RequestParam;  
        import org.springframework.web.multipart.MaxUploadSizeExceededException;  
        import org.springframework.web.multipart.MultipartFile;  
        import org.springframework.web.servlet.HandlerExceptionResolver;  
        import org.springframework.web.servlet.ModelAndView;  
        import org.springframework.web.servlet.view.RedirectView;  
        import cn.ac.iscas.gz.nssc.base.domain.UploadForm;  
        /** 
        * @ClassName: UploadFormController 
        * @Description: 文件上传控制器controller 
        * @author xuzhongming Email: xuzhongming@gz.iscas.ac.cn 
        * @date 2012-2-23 - 下午3:34:43 
        * @version : 1.0 
        */  
        @Controller  
        @RequestMapping(value = "/FileUploadForm.do")  
        public class UploadFormController {  
                @RequestMapping(params = "method=uploadAjax")  
                public void uploadAjax(@RequestParam(value = "file") MultipartFile file,  
                                HttpServletRequest request, HttpServletResponse response) {  
                        String uploadDirPath = request.getSession().getServletContext()  
                                        .getRealPath("/upload");  
                        MultipartFile image = file;  
                        File destFile = new File(uploadDirPath + "/"  
                                        + image.getOriginalFilename());  
                        try {  
                                FileCopyUtils.copy(image.getBytes(), destFile);  
                        } catch (IOException e) {  
                                e.printStackTrace();  
                        }  
                        String destPath = request.getContextPath() + "/upload/"  
                                        + destFile.getName();  
                        try {  
                                JSONObject jsonObject = new JSONObject();  
                                jsonObject.put("path", destPath);  
                                response.setContentType("text/html");  
                                response.getWriter().println(jsonObject.toString());  
                        } catch (IOException e) {  
                                e.printStackTrace();  
                        }  
                }  
        }  

4.在配置文件中注册

    <!-- Configure the multipart resolver -->  
      <bean id="multipartResolver"  
           class="org.springframework.web.multipart.commons.CommonsMultipartResolver"  
                   p:defaultEncoding="utf-8"   
           >  
          <!-- one of the properties available; the maximum file size in bytes -->  
          <property name="maxUploadSize" value="1024000"/>  
      </bean>  

这样就可以实现文件的上传了。

5.实现效果如下所示:

捕获100.PNG

 



参考地址:
                   http://blog.youkuaiyun.com/sundenskyqq/article/details/6799038
                    http://www.open-open.com/home/space-668-do-blog-id-5708.html
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值