spring MVC 文件上传下载的实现

            最近在使用springmvc框架完成文件上传下载功能,就我遇到的问题做一些总结,在此与大家分享一下,希望对遇到同样问题的你有帮助。

     1、文件上传

1.1、springmvc配置文件

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="excludeUrls">
            <array>
                <value>/ueditor/dispatch</value>
            </array>
        </property>
        <!--one of the properties available;the maximum upload size in bytes 100M -->
        <property name="maxUploadSize" value="104857600"/>
        <property name="maxInMemorySize" value="40960"></property>
        <property name="defaultEncoding" value="utf-8"></property>
    </bean>

1.2 、上传页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!--这边引用easyui的一些css和插件-->
<%@include file="/WEB-INF/jsp/common/taglibs.jspf"%>
<!--form记得配置 enctype="multipart/form-data"-->
<form id="form" cssClass="form" commandName="Attachment" action="${pageContext.servletContext.contextPath}/xxxController/uploadFile"   enctype="multipart/form-data" method="post">
	<table align="center">
		<tr>
		<td>附件</td>
		<td>
			<input  name="file" id="file" class="easyui-filebox"   data-options="prompt:'选择文件'" multiple/><!--设置mutiple,可以按住ctrl多选文件-->
		</td>
	</tr>
		<tr>
			<td></td>
			<td>提示:若要上传多个文件,请按住ctrl键多选文件上传即可。</td>
		</tr>
	</table>
	<script type="text/javascript">
		$(document).ready(function(){
		    $("#file").filebox({
				buttonText:'选择文件'
			})
		})
	</script>
</form>

1.3、Controller

@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
public AjaxResponse uploadFile(@ModelAttribute("Attachment") Attachment m, @RequestParam("file") MultipartFile files[]) {
        InputStream fileIS= null;
        if(files!=null&&files.length>0){
            for (int i = 0; i < files.length; i++) {
                MultipartFile file = files[i];
                if (!file.isEmpty()) {
                // 获得原始文件名
                String originalFilename = file.getOriginalFilename();
                //需要保存的文件名
                String filename=originalFilename.substring(0,originalFilename.lastIndexOf("."));
                attachment.setFileName(filename);
                //文件后缀
                String fileType = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);//txt
                attachment.setFileType(fileType);
                try {
                    fileIs = file.getInputStream();
                    byte[] b = FileCopyUtils.copyToByteArray(fileIS);
                    if (b.length > 0) {
                        attachment.setAttachmentFile(b);//将文件存入数据库,byte[]类型字段对应数据库为blob
                    }
                    attachmentMapper.saveAttachment(attachment);
                } catch (IOException e) {
                     AjaxResponse res = AjaxResponse.fail("对不起,附件上传时出错了!");
            				return res;
                }
                }
            }
        }
        AjaxResponse res = AjaxResponse.success("保存成功");
        return res;
    }

 1.4、提交方式可以选择form表单提交,也可以选择ajax提交,但是如果使用ajax提交需要注意的是下面代码中列的三点。

function uploadFile(){
    								var formData=new FormData($('#form')[0]);
                    var file=formData.get("file");
                    if(file.size==0){
                        $.messager.alert("请选择文件!");
                        return false;
                    }
                    $.ajax({
                        url: "${pageContext.servletContext.contextPath}/xxxController/uploadFile",
                        data:formData,//1、使用FormData
                        processData:false,//2、不处理发送的数据
                        contentType:false,//3、不要设置Content-Type请求头
                        success : function(res) {
                           if (responseStr.code == "0") {
                               $.messager.alert(res.message);
                           } else {
                               $.messager.alert(res.message);
                           }
                        }
                    });
                    
                    }

2、文件下载

2.1、springmvc配置(下载出文件内容出现乱码问题,记得配置下列内容)

 <mvc:message-converters register-defaults="true">
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <constructor-arg value="UTF-8"/>
            </bean>
            <!-- 避免IE执行AJAX时,返回JSON出现下载文件 -->
            <bean id="fastJsonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
                <property name="features">
                    <array>
                        <value>WriteMapNullValue</value>
                        <value>WriteNullStringAsEmpty</value>
                        <value>WriteDateUseDateFormat</value>
                    </array>
                </property>
                <property name="supportedMediaTypes"><!-- 解决文件内容乱码问题 -->
                    <list>
                        <value>application/json;charset=UTF-8</value>
                        <value>text/plain;charset=UTF-8</value>
                    </list>
                </property>
            </bean>
        </mvc:message-converters>

2.2、页面就不在赘述了,可以选择超链、按钮等等。因为所使用的框架原因,避免使用ajax提交,所以选择虚拟form表单的形式来提交。

function downloadFile() {
            var row = $grid.datagrid("getSelected");
            if (row == null) {
                showNoSelectWarn();
                return false;
            }
                var form = $("<form>"); //定义一个form表单
                form.attr('style', 'display:none');   
                form.attr('target', '');
                form.attr('method', 'post');
                form.attr('action', "${pageContext.servletContext.contextPath}/xxxController/uploadFile/xxxController/downloadFile");
                var input = $('<input>'); //需要传入的参数
                input.attr('type', 'hidden');
                input.attr('name', 'attachmentId');
                input.attr('value', row.attachmentId);
                $('body').append(form);  
                form.append(input);   
                form.submit();
        }

2.3、Controller

@RequestMapping(value = "/downloadFile")
    @ResponseBody
    public ResponseEntity<byte[]> downloadFile(String attachmentId) {
        Attachment attachment= attachmentService.getAttachment(attachmentId);
        byte[] attachmentFile = attachment.getAttachmentFile();//数据库存的文件
        String fileName=attachment.getFileName();//文件名
        String fileType=attachment.getFileType();//文件后缀
        //设置请求头内容,告诉浏览器代开下载窗口
        HttpHeaders headers = new HttpHeaders();
        try {
        //下载时显示文件的名称格式aa.txt,并解决文件名称中文乱码问题
        headers.setContentDispositionFormData("attachment", URLEncoder.encode(fileName, "UTF-8") + "." + fileType);
        }catch (Exception e)
        {
            e.printStackTrace();
        }
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<byte[]>(attachmentFile,
                headers, HttpStatus.OK);
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值