Spring MVC+ajaxfileupload实现文件上传下载

11 篇文章 0 订阅
6 篇文章 0 订阅

一、框架相关

1、jar包引入
首先引入common-fileupload.jar文件,但是因为common-fileupload是依赖于common-io这个包的
而commons-lang3包含common-io包
因此引入commons-lang3与common-fileupload即可

<dependency>
     <groupId>commons-fileupload</groupId>
     <artifactId>commons-fileupload</artifactId>
     <version>1.3.1</version>
</dependency>
<dependency>
     <groupId>org.apache.commons</groupId>
     <artifactId>commons-lang3</artifactId>
     <version>3.1</version>
</dependency>

2、在Spring MVC配置文件中配置上传功能

<!--需要文件上传功能时,启用以下配置-->
<beanid="multipartResolver"   class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
     <propertyname="maxInMemorySize">
        <value>1638400</value>
     </property>
</bean>

二、前台相关
1、前台ajaxfileupload插件引入

<script src="ajaxfileupload.js" type="text/javascript"></script>

2、前台HTML代码

<input type='file' id='imgUpload' name='imgUpload'/>

3、前台JS代码
给按钮定义事件,包括以下代码。
注意此处的fileElementId与前面input的id一致

$.ajaxFileUpload({
    url:urlPath,
    type:"POST",
    secureuri:false,
    fileElementId:'imgUpload',
    data:postParam,
    dataType:"JSON",
    cache:false,
    error:function(data){
        layer.open({
            title:'提示信息',
            content:'表单数据不合法!'
        });
    },
    success:function(data){
    }
});

三、上传代码
1、Controller层

/**
 * 创建菜单
 * @param menuBean MenuBean
 * @param uploadFile 上传文件
 * @param request 请求
 * @return 是否成功
 * @throws IOException, BizException
 */
@RequestMapping(value = "save", method = RequestMethod.POST)
public @ResponseBody String createMenu(MenuBean menuBean,
                                       @RequestParam(value = "imgUpload") MultipartFile uploadFile,
                                       HttpServletRequest request) throws IOException, BizException {
    String contextPath = request.getSession().getServletContext().getRealPath("/uploadFile");
    return sysMenuService.saveMenu(menuBean, uploadFile, contextPath);
    }

2、Service层

/**
 * 创建菜单
 * @param menuBean menuBean
 * @param uploadFile 上传文件
 * @param ContextPath 上传路径
 * @return 是否成功
 * @throws BizException, IOException
 */
@Override
@Transactional(readOnly = false)
public String saveMenu(MenuBean menuBean, MultipartFile uploadFile,
                       String ContextPath) throws BizException, IOException {

    //创建实体对象,用于保存数据库
    SysMenuEntity sysMenuEntity = new SysMenuEntity();
    BeanUtils.copyProperties(menuBean, sysMenuEntity);

    //保存文件
    String fileSaveFlag = FileSave(sysMenuEntity, uploadFile, ContextPath);
    if (!Constants.SAVE_SUCCESS.equals(fileSaveFlag)) {
        return fileSaveFlag;
    }

    //设置当前菜单序号
    sysMenuEntity.setMenuCd(sysMenuDao.MenuCdAutoIncrease());

    //保存数据
    sysMenuDao.save(sysMenuEntity);

    return Constants.SAVE_SUCCESS;
}

/**
 * 文件上传方法
 * @param sysMenuEntity 菜单实体
 * @param uploadFile 上传文件
 * @param ContextPath 上传路径
 * @return 是否成功
 * @throws IOException
 */
@Transactional(readOnly = false)
public String FileSave(SysMenuEntity sysMenuEntity,
                       MultipartFile uploadFile,
                       String ContextPath) throws IOException {

    if (!uploadFile.isEmpty()) {
        //获取文件大小
        Long size = uploadFile.getSize();

        //判断上传文件大小是否 满足配置
        if (uploadFileConfig.getMaxUploadSize() < size) {
            return Constants.FILE_SIZE_ERROR;
        }

        //获取文件的文件名
        String filename = uploadFile.getOriginalFilename();

        //获取文件扩展名
        String fileSuffix = StringUtils.substringAfterLast(filename, Constants.SPOT);

        //判断扩展名是否符合要求 
        if (StringUtils.isBlank(uploadFileConfig.getAllowFileType()) ||                  !StringUtils.containsIgnoreCase(uploadFileConfig.getAllowFileType(), fileSuffix)) {
            return Constants.FILE_TYPE_ERROR;
        }

        //设定一个序列以作为存储文件名
        String fileName = UUID.randomUUID().toString() + Constants.SPOT + fileSuffix;

        //创建保存文件路径的File对象
        File uploadFoler = new File(ContextPath);

        //创建目的File对象
        File targetFile;

        if (!uploadFoler.exists()) {
            FileUtils.forceMkdir(uploadFoler);
        }
        targetFile = new File(uploadFoler, fileName);

        // 把文件重命名,上传到该目录下面,将上传文件写到服务器上指定的文件。
        uploadFile.transferTo(targetFile);

        //定义附件实体
        SysFileEntity sysFileEntity = new SysFileEntity();   
        sysFileEntity.setFileName(filename);  sysFileEntity.setFilePath(targetFile.getPath().split("uploadFile")[1]);
        long fileSEQ = sysFileDao.save(sysFileEntity);

        sysMenuEntity.setFileSeqId(fileSEQ);

        return Constants.SAVE_SUCCESS;
    } else {
        return Constants.SAVE_SUCCESS;
    }
}

四、上传可能用到的配置类或文件
1、fileUploadConfig.properties
上传相关配置,如上传路径、最大文件长度、允许上传扩展名

file.maxUploadSize = 1000000000000
file.uploadPath = d:/upload_path
file.maxFileSize = 8
file.allowFileType = bmp,gif,jpg,jpeg,jpeg2000,tiff,psd,swf,svg,png

2、UploadFileConfig.java
配置文件读取类,用于读取fileUploadConfig.properties 内value值

package com.study.base.common.upload;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * Created by Administrator on 15-11-11.
 */
@Component
public class UploadFileConfig {

    @Value("${file.maxUploadSize}")
    private String maxUploadSize;

    @Value("${file.uploadPath}")
    private String uploadPath;

    @Value("${file.maxFileSize}")
    private String maxFileSize;

    @Value("${file.allowFileType}")
    private String allowFileType;


    public Long getMaxUploadSize() {
        return Long.valueOf(maxUploadSize);
    }

    public void setMaxUploadSize(Long maxUploadSize) {
        this.maxUploadSize = String.valueOf(maxUploadSize);
    }

    public String getUploadPath() {
        return uploadPath;
    }

    public void setUploadPath(String uploadPath) {
        this.uploadPath = uploadPath;
    }

    public Integer getMaxFileSize() {
        return Integer.valueOf(maxFileSize);
    }

    public void setMaxFileSize(Integer maxFileSize) {
        this.maxFileSize = String.valueOf(maxFileSize);
    }

    public String getAllowFileType() {
        return allowFileType;
    }

    public void setAllowFileType(String allowFileType) {
        this.allowFileType = allowFileType;
    }
}

5、下载代码

/**
 * 根据要下载的文件名称
 * 上服务器的目录下,下载该文件
 * @param request 请求
 * @param response 响应
 * @throws IOException
 */
@RequestMapping("/download")
public void download(HttpServletRequest request,
                     HttpServletResponse response) {

    OutputStream os = null;
    InputStream inputStream = null;
    try{
        //设置头部信息
        String file_Name = java.net.URLDecoder.decode(request.getParameter("fileName"), Constants.UTF8);
        String fileRealName = java.net.URLDecoder.decode(request.getParameter("fileRealName"), "UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition", "attachment;fileName="+ new String(fileRealName.getBytes("gb2312"), "iso8859-1"));

        //拼接下载路径
        String path = request.getSession().getServletContext().getRealPath("/uploadfile") +file_Name;

        //创建读取流
        inputStream = new FileInputStream(new File(path));
        os = response.getOutputStream();

        //读取数据
        byte[] b = new byte[2048];
        int length;
        while ((length = inputStream.read(b)) > Constants.ZERO_SIZE) {
            os.write(b, 0, length);
        }
    }catch(IOException e){
        log.error(e);
    }finally{
        // 关闭
        if(os != null){
            try {
                os.close();
            } catch (IOException e) {
                log.error(e);
            }
        }
        if(inputStream != null){
            try {
                inputStream.close();
            } catch (IOException e) {
                log.error(e);
            }
        }
    }
}
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值