一,上传文件
1 在pom.xml中加入以下
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3</version>
</dependency>
2 在jsp上,由于上传插件本身都是汉字,为了设置自己想要的字眼可以隐藏它,通过两个input来实现。也可以实现多文件上传,只需要在MultipartFile下面继续添加input。
<form id="applyForm" name="applyForm" class="validateForm" enctype="multipart/form-data">
<!-- 一定加入 enctype="multipart/form-data",相当于识别标志 -->
<div style="float:left" >
<input noValidate type="button" value="<spring:message code="register.uploadLicense"/>" onclick="document.applyForm.picpath.click()">
<input noValidate name="path" id="path" readonly>
</div> <br>
<div class="input-groups" id="MultipartFile">
<input type="file" noValidate class="form-input" size="5242880" id="picpath" name="picpath" style="display:none;" onChange="tras()"
accept="image/jpg,image/jpeg,image/png,image/bmp,application/zip,application/x-rar-compressed,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-powerpoint,text/plain,application/pdf" >
</div>
3,在js上,把文件放入myfiles里面
function tras(){
//alert(vl);
var pa = $("#picpath").val();
//alert(pa);
var ars = new Array();
ars = pa.split("\\");
var path = ars[ars.length-1];
//alert(path);
$("#path").val(path);
}
/** *******企业资料上传 js********* */
$("#MultipartFile input").change(function(e) {
var name = $(this).attr("name");
var max = 5;
var value = $(this).val();
if (value) {
var file = $(this).get(0).files[0];
var size = parseInt(file.size);
var reg = new RegExp(
"(.jpg|.jpeg|.png|.bmp|.doc|.docx|.xls|.xlsx|.ppt|.txt|.pdf|.zip|.rar)");
var match_rel = reg.test(value);
// var
// index=value.indexOf(".jpg")>0||value.indexOf("")>0||value.indexOf("")>0||value.indexOf("")>0||value.indexOf("")>0||value.indexOf("")>0||value.indexOf("")>0||value.indexOf("")>0||value.indexOf("")>0||value.indexOf("")||value.indexOf("")||value.indexOf("")||value.indexOf("");
console.log(match_rel);
if (match_rel) {
if (size > max * 1024 * 1024) {
$(this).val("").removeAttr("name");
$("#MultipartFile").after("<p class='errorEle'>"+i18n['accept5m']+"</p>");
} else {
$(this).attr("name", "myfiles");
}
} else {
$(this).val("");
$("#MultipartFile").after("<p class='errorEle'>"+i18n['specification']+"</p>");
}
} else {
$(this).removeAttr("name");
$(this).val("");
}
;
})
//加入一个提交表单的ajax即可
$("#applyForm").ajaxSubmit({
type : "post",
url : ctx + "/user/register.shtml",
dataType : "json",
success : function(data) {
if (data.state == '200') {
}
})
4,后台controller
@RequestMapping("/register")
public void register(User user, HttpServletRequest request, HttpServletResponse response,@RequestParam MultipartFile[] myfiles) throws Exception {
Map<String, Object> map = new HashMap<>();
try {
String upload = FileUtil.upload(myfiles,dir, request);
if ("true".equals(upload.split("=")[0])) {
if (upload.length() > 6) {
path = upload.split("[=]")[1];
String[] split = path.split("[+]");
switch (split.length) {
case 1:
user.setLicense(split[0]);
break;
default:
break;
}
}
} else if("empty".equals(upload.split("=")[0])) {
// 打印错误信息{文件上传失败}
map.put("state", "30119");
map.put("msg", wcu.getValue("code.30119", request));
HtmlUtil.writerJson(response, map);
return;
}
} catch (Exception e) {
e.printStackTrace();
map.put("state", CodeConst.EXCEPTION_516.getState());
map.put("msg", wcu.getValue("code.516", request));
HtmlUtil.writerJson(response, map);
}
}
FileUtil.java
package com.apk.openUser.utils;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;
public class FileUtil {
private final static Logger logger = LoggerFactory
.getLogger(FileUtil.class);
private final static String file_path = PropertyUtil.getProperty("file_path");
/**
* 多文件上传
* @param myfiles
* @param request
* @return
* @throws Exception
*/
public static String upload(MultipartFile[] myfiles,String dir,HttpServletRequest request) throws Exception{
String msg = "true";
StringBuffer path = new StringBuffer();
if (myfiles==null||myfiles.length==0) {
msg="empty=文件不能为空";
}
System.out.println(myfiles.length);
for (MultipartFile myfile : myfiles) {
System.out.println(myfile);
if (myfile.isEmpty()) {
msg = "empty=文件不能为空";
} else {
String fileName = myfile.getOriginalFilename();
String lastName = fileName.substring(fileName.lastIndexOf(".") + 1,fileName.length());
if(NetCheckFieldsUtil.isRight(lastName)){
// 如果用的是Tomcat服务器,则文件会上传到\\%TOMCAT_HOME%\\webapps\\YourWebProject\\WEB-INF\\upload\\文件夹中
/*String realPath = request.getSession().getServletContext()
.getRealPath("/WEB-INF/myfiles");*/
// 这里不必处理IO流关闭的问题,因为FileUtils.copyInputStreamToFile()方法内部会自动把用到的IO流关掉,我是看它的源码才知道的
//String file_path1 = file_path+File.separator+dir;
File folder = new File(file_path);
if (!folder.exists() && !folder.isDirectory()) {
logger.info("文件夹路径不存在,创建路径:" + folder);
folder.mkdirs();
}
//用base加密防止Linux乱码
BASE64Encoder encoder = new BASE64Encoder();//用base防止在Linux下中文乱码
String fileN = encoder.encode((dir+fileName).getBytes());
System.out.println("fileNames:"+fileN);
FileUtils.copyInputStreamToFile(myfile.getInputStream(),
new File(file_path, fileN));
//数据保存为 myfilesHydrangeas.jpg,D:\ztyq-open\apply-open-web\src\main\webapp\WEB-INF\myfiles\Hydrangeas.jpg
//path.append(fileName).append(",").append(UUID.randomUUID().toString().replace("-", "")).append(".").append(lastName).append("+");
path.append(fileName).append("+");
}else{
logger.error("文件格式不支持请重新选择");
msg = "401=文件格式不支持请重新选择";
}
}
}
msg = msg + "=" + path.toString();
System.out.println("MSG:::"+msg);
return msg;
}
/**
* 下载文件
* @param filepath
* @param response
* @param request
* @throws Exception
*/
public static void downloadPath(String dir,String fileName,HttpServletResponse response,HttpServletRequest request) throws Exception {
BASE64Encoder encoder = new BASE64Encoder();
String fileN = encoder.encode((dir+fileName).getBytes());
File file = new File(file_path+File.separator+fileN);//File.separator是自动识别系统路径中斜杠的写法。
InputStream inputStream;
inputStream = new BufferedInputStream(new FileInputStream(file));
byte[] buffer = new byte[inputStream.available()];
inputStream.read(buffer);
inputStream.close();
response.reset();
String fileNames="";
System.out.println(request.getHeader("User-Agent").toLowerCase());
//System.out.println(request.getHeader("User-Agent").toUpperCase());
String agent = request.getHeader("User-Agent").toLowerCase();
if (agent.indexOf("msie") > 0||agent.indexOf("edge")>0||(agent.indexOf("like gecko")>0&&agent.indexOf("chrome")==-1)) {
fileNames = URLEncoder.encode(fileName, "UTF-8");// IE浏览器
}else{
fileNames = new String(fileName.getBytes("UTF-8"), "ISO8859-1");// 谷歌
}
System.out.println(fileNames);
//System.out.println(new String(filenames.getBytes("UTF-8"), "ISO-8859-1"));
// 先去掉文件名称中的空格,然后转换编码格式为utf-8,保证不出现乱码,这个文件名称用于浏览器的下载框中自动显示的文件名
response.addHeader("Content-Disposition", "attachment;filename=" + fileNames);
response.addHeader("Content-Length", "" + file.length());
OutputStream os = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
os.write(buffer);// 输出文件
os.flush();
os.close();
}
}
二,下载文件
1,jsp上,注意传的参数值尽量简单是个数字不含有中文,如果有中文IE浏览器上直接报400.
<a href="${ ctx }/auditor/downloadFile.do?id=${session_user.id}">
2,controller
@RequestMapping("/downloadFile")
public void downloadFile(String id, HttpServletResponse response, HttpServletRequest request) throws Exception {
int id1 = Integer.parseInt(id);
User user = userService.queryUserById(id1);
String fileName = user.getLicense();
response.setCharacterEncoding("utf-8");
response.setContentType("application/octet-stream;charset=utf-8");
response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
System.out.println("fileName:"+fileName);
FileUtil.downloadPath(user.getUsername(),fileName, response, request);
}
}