记录一下做这个功能时遇到的一些问题
1、想用ajax写,其中写到onclick时报语法错误,因为传参是字符串所以加双引号,这时外面只能加单引号,要注意不可以都用双引号,不然它不清楚哪个是一对会报错。语法:onclick='upload("${}","{}","{}")'
2、ajax方式写的没有下载成功,原来是因为ajax方式请求的数据只能存放在javascipt内存空间,可以通过javascript访问,但是无法保存到硬盘,因为javascript不能直接和硬盘交互,否则将是一个安全问题。
3、响应头要写好,response.setHeader("Content-Disposition",openStyle+";filename="+ URLEncoder.encode(fileLog.getOldfilename(),"UTF-8"));
不要缺少分号,Content-Disposition属性有两种类型:inline 和 attachment,inline代表直接打开就是预览,attcahment是下载,openStyle传了具体属性值。
下面贴出具体步骤和核心代码
导入依赖,commons-fileupload,commion-io,这是用来文件上传的,里边有好多类和方法用来写文件上传比较方便。
配置文件
<!--配置文件上传-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="1048576"></property>
</bean>
jsp页面
<!--文件上传提交方式必须是post,enctype的值必须是“multipart/form-data”-->
<form action="${APP_PATH}/fileLog/uploadFile" method="post" enctype="multipart/form-data">
<input type="file" name="file"/>
<input type="subbmit" value="提交"/>
</form
controller
package com.lz.controller;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lz.entity.FileLog;
import com.lz.service.FileLogService;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMap