源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

SpringMvc3+extjs4实现上传与下载功能

  • 时间:2020-05-25 18:14 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:SpringMvc3+extjs4实现上传与下载功能
最近生活过的很充实,人一直在不停的忙碌着学习新东西。这是我最近遇到的问题,我找度娘n了很久,终于找到了解决方案! 前台代码:
<script>  
 Ext.onReady(function() {

    Ext.create('Ext.form.Panel', {
      title : '文件上传',
      width : 400,
      bodyPadding : 10,
      frame : true,
      renderTo : document.body,
      items : [ {
        xtype : 'filefield',
        name : '文件',
        fieldLabel : 'File',
        labelWidth : 50,
        msgTarget : 'side',
        allowBlank : false,
        anchor : '100%',
        buttonText : '请选择文件...'
      } ],

      buttons : [ {
        text : '上传',
        handler : function() {
          var form = this.up('form').getForm();
          if (form.isValid()) {
            form.submit({
              url : '根路径/fileUploadDown/fileUpload',
              waitMsg : '正在上传文件中...',
              success : function(fp, o) {
                Ext.Msg.alert('上传文件成功!');
              }
            });
          }
        }
      } ]
    });

  });
</script>
后台代码:
/**
*记录返回结果*/
 class ExtJSFormResult {

  private boolean success;

  public boolean isSuccess() {
    return success;
  }

  public void setSuccess(boolean success) {

  }

  public String toString() {
    return "{success:" + this.success + "}";
  }
}
 

class FileUploadBean {

    private CommonsMultipartFile file;

    public CommonsMultipartFile getFile() {
      return file;
    }

    public void setFile(CommonsMultipartFile file) {
      this.file = file;
    }
}

/**
 * 文件的上传与下载
 * @author Administrator
 *
 */
@Controller
@RequestMapping(value = "/fileUploadDown")
public class FileUploadAndDownController {
  
  private static int countter=1; //定义一个计数器,用于上传文件的重命名
  
  @Autowired
  private ProAnnexDao<ProAnnex> proAnnextDao;
  
  

  public void setProAnnextDao(ProAnnexDao<ProAnnex> proAnnextDao) {
    this.proAnnextDao = proAnnextDao;
  }

  @RequestMapping(value="fileUpload",method = RequestMethod.POST)
  public @ResponseBody String create(RedirectAttributes redirectAttributes,FileUploadBean uploadItem, 
      BindingResult result,HttpSession session){
    //获取根路径
    String uploadFolderPath = session.getServletContext().getRealPath("/"); 
    ExtJSFormResult extjsFormResult = new ExtJSFormResult();
    try {
      
      if (result.hasErrors()) {
        for (ObjectError error : result.getAllErrors()) {
          System.err.println("Error: " + error.getCode() + " - "
              + error.getDefaultMessage());
        }

        // 设置ExtJS返回 - error
        extjsFormResult.setSuccess(false);

        return extjsFormResult.toString();
      }

      MultipartFile file = uploadItem.getFile();
      String fileName = null;
      InputStream inputStream = null;
      OutputStream outputStream = null;
      if(file.getSize()>0){
         System.out.println("File Size:::" + file.getSize());
        if(file.getSize()>5242880){
           System.out.println("File Size:::" + file.getSize());
           extjsFormResult.setSuccess(false);
          return "error";
        }
        
       inputStream = file.getInputStream();
    
       File newFile = new File(uploadFolderPath + "fileUpload/");
       //如果文件路径不存在就新建一个
       if(!newFile.exists()){
         newFile.mkdirs();
       }
       //获取文件名
       String name=file.getOriginalFilename();
       //从数据库中查询存在此类文件名否
        Long count=proAnnextDao.isRepeatName(name);
        //如果存在一样的文件名,就进行从命名
        if (count>0) {
          name=name.substring(0, name.lastIndexOf("."))+"("+(countter++)+")"+name.substring(name.lastIndexOf("."));
        }
        
        fileName = uploadFolderPath + "fileUpload/" + name;
        outputStream = new FileOutputStream(fileName); 
        int readBytes = 0;
        byte[] buffer = new byte[10000];
        while ((readBytes = inputStream.read(buffer, 0, 10000)) != -1) {
            outputStream.write(buffer, 0, readBytes);
        }
        
        outputStream.close();
        inputStream.close();
       
        
      }

      // 设置ExtJS返回 - sucsess
      extjsFormResult.setSuccess(true);
    } catch (Exception e) {
      
      e.printStackTrace();
      // 设置ExtJS返回 - error
    
      extjsFormResult.setSuccess(false);
    }
    

    return extjsFormResult.toString();
  }
  

}

springMvc.xml(此文件名可能跟项目的实际情况有区别)中的配置:
<!-- 上传文件,限制大小的配置 -->
   <bean id="multipartResolver"
    class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
     <!--resolveLazily属性启用是为了推迟文件解析,以便在Upload中捕获文件大小异常-->
    <property name="resolveLazily" value="true"/>
    <property name="maxUploadSize" value="5242880" />
  </bean>
  
  
  <!-- 将无法mapping到Controller的path交给default servlet handler处理   -->  
  <mvc:default-servlet-handler/><!-- 使用默认的servlet来响应静态文件 -->
  <!-- 文件的上传与下载 -->
  <mvc:view-controller path="/" view-name="redirect:/fileUploadDown"/>

以上的就是上传文件了。  那[b]下载[/b]呢? 下载比较简单,代码如下:
@RequestMapping("/downloadFile") 
  public void download(@Valid @ModelAttribute("downLoadName") String downLoadName,
      HttpServletResponse response,HttpSession session,BindingResult result,HttpServletRequest request) throws IOException { 
    
    response.setCharacterEncoding("UTF-8");
    request.setCharacterEncoding("UTF-8");
    //获取文件的路径
    String url=session.getServletContext().getRealPath("/")+"/fileUpload/"+downLoadName;
    System.out.println(url);
    File file=new File(url);
    
    InputStream input = FileUtils.openInputStream(file); 
    byte[] data = IOUtils.toByteArray(input); 
 
    //System.out.println("文件名:"+downLoadName);
    response.reset(); 
   //设置响应的报头信息(中文问题解决办法)
    response.setHeader("content-disposition","attachment;fileName="+URLEncoder.encode(downLoadName, "UTF-8"));
    response.addHeader("Content-Length", "" + data.length); 
    response.setContentType("application/octet-stream; charset=UTF-8"); 
    
    IOUtils.write(data, response.getOutputStream()); 
    IOUtils.closeQuietly(input); 
    
  }
在界面上只要有一个连接地址:如:window.location.href="根路径/fileUploadDown/downfile/downLoadName=" rel="external nofollow" +name;这样就可以下载了....   超连接的写法基本一样,这里就不多说了。 以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程素材网。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部