1先写一个文件上传的页面
<%@ page language="java" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<c:set var="ctx" value="${pageContext.request.contextPath}"/>
<html>
<head>
<title><fmt:message key="home.title"/></title>
<jsp:directive.include file="/common/taglibs.jsp" />
<script src="${ctx}/scripts/plugins/jquery-validation/dist/jquery.validate.min.js" type="text/javascript"></script>
<script src="${ctx}/scripts/plugins/jquery-validation/dist/form_validator.js" type="text/javascript"></script>
<script type="text/javascript" src="${ctx}/scripts/version/modVersion.js"></script>
</head>
<style>
.formcss{
width: 200px!important;
margin-left: 0px!important;
height: 40px!important;
}
</style>
<body class="home">
<!-- BEGIN PAGE CONTENT-->
<div class="col-md-12">
<!-- BEGIN TAB PORTLET-->
<div class="portlet box green">
<div class="portlet-title">
<div class="caption">
<i class="fa fa-reorder "></i><fmt:message key="menu.motion.version"/>
</div>
</div>
<div class="portlet-body form" id="formDiv">
<form:form commandName="version" method="post" action="${ctx}/version/saveVersion"
id="versionModForm" cssClass="form-horizontal" enctype="multipart/form-data">
<div class="form-body">
<div class="alert alert-danger display-hide">
<button class="close" data-close="alert"></button>
<fmt:message key="message.form.error"/>
</div>
<div class="form-group" >
<label class="control-label col-md-3"><fmt:message key="audio.name"/>
</label>
<div class="col-md-4 input-icon">
<form:hidden path="vsId" />
<form:hidden path="createTime" />
<input id="vsName" name="vsName" type="text" class="form-control" style="width:240px;margin-left: 0px;height: 38px" placeholder="输入名称" >
</div>
</div>
<div class="form-group" >
<label class="control-label col-md-3"><fmt:message key="audio.type"/>
</label>
<div class="col-md-4 input-icon">
<input id="vsType" name="vsType" type="text" class="form-control" style="width:240px;margin-left: 0px;height: 38px" placeholder="输入类型" >
</div>
</div>
<div class="form-group" >
<label class="control-label col-md-3">备注
</label>
<div class="col-md-4 input-icon">
<input id="remark" name="remark" type="text" class="form-control" style="width:240px;margin-left: 0px;height: 38px" placeHolder="备注"/>
</div>
</div>
<div class="form-group" style="width: 800px">
<label class="control-label col-md-3"><fmt:message key="command.file.name"/>
<span class="required">
</span>
</label>
<div class="col-md-4" style="width:800px">
<div class="file-box">
<input type='text' style="width:240px;margin-left: 0px;height: 38px" name='textfield' id='textfield' class='txt' />
<%-- <input type='button' class='btn green' value='<fmt:message key="monobj.file.browse"/>...' />--%>
<input type="file" name="myfile"<%-- class="file"--%> id="fileField" size="28" onchange="imputPicRun(this);" />
</div><br/>
</div>
</div>
</div>
<div class="form-actions fluid">
<div style="margin-left: 138px" class="col-md-offset-3 col-md-9">
<button type="submit" class="btn green"><fmt:message key="button.save"/></button>
<button type="button" class="btn blue" onclick="history.go(-1)"><fmt:message key="common.button.goback"/></button>
</div>
</div>
</form:form>
<!-- END FORM-->
</div>
</div>
<!-- END TAB PORTLET-->
</div>
<!-- END PAGE CONTENT-->
<div id="deptList"></div>
<script>
colHeight = total-31-document.getElementById("formDiv").offsetTop;
$("#formDiv").css({ height: (colHeight-7)+"px" });
</script>
</body>
</html>
2.提交文件到后台的处理方法
package com.xexun.webapp.controller;
import com.xexun.Constants;
import com.xexun.model.beetl.TermHttpVersion;
import com.xexun.service.TermHttpVersionBeetlManager;
import com.xexun.utils.FileUtil;
import com.xexun.vo.FileInfo;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.Date;
/**
-
@author :Qk.
-
@ Date :Created in 14:34 2020/4/22
-
@ Description:
-
@ Modified By:
-
@ Version:
/
@Controller
@RequestMapping("/version")
public class TermHttpVersionController {
@Resource
private TermHttpVersionBeetlManager termHttpVersionBeetlManager;
@RequestMapping(“upgrade”)
public ModelAndView toAddVersion(HttpServletRequest request,@ModelAttribute(“version”) TermHttpVersion termHttpVersion){
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("/version/modVersion");
return modelAndView;
}
@RequestMapping(“saveVersion”)
public String saveVersion(@ModelAttribute(“version”) TermHttpVersion termHttpVersion,
@RequestParam(“myfile”) MultipartFile myfile,
HttpServletRequest request) {
/***************************/
String orinPath = Constants.VERSION_PATH;
//这里获取的项目下的路径,将用来存储文件
String filePath = request.getServletContext().getRealPath(orinPath);
File myFile = new File(filePath);
if (!myFile.exists()) {
myFile.mkdirs();
}
//获取的是文件的名字
String fileName = myfile.getOriginalFilename();
//获取文件的类型
String contentType = myfile.getContentType();
InputStream is = null;
try {
//获取文件输入流
is = myfile.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
//这里将文件上床的东西封装到实体对象中
FileInfo fileInfo = new FileInfo(termHttpVersion.getVsName(), contentType, filePath, is);
if (!StringUtils.isEmpty(fileInfo.getFileName())) {
//这里实现的文件的上传
FileUtil.fileUploadNoImg(fileInfo);
termHttpVersion.setVsUrl( Constants.VERSION_PATH+termHttpVersion.getVsName());
termHttpVersion.setCreateTime(new Date());
termHttpVersion.setVsSize(myfile.getSize());
byte[] aa=null;
try {
//这里是文件已经上传后的文件
File myFile1 = new File(filePath+"/"+fileName);
//这里的方法将文件转化成字节
aa=InputStreamTOByte(new FileInputStream(myFile1), (int) myfile.getSize());
} catch (IOException e) {
e.printStackTrace();
}
//这里用了一个多线程异步的方法将数据写道redis
termHttpVersionBeetlManager.saveAndRedis(termHttpVersion,aa);
}
return “redirect:…/commons/success?reurl=motion/versions”;
}
// 将InputStream转换成byte数组
public byte[] InputStreamTOByte(InputStream in,int size) throws IOException {ByteArrayOutputStream outStream = new ByteArrayOutputStream(); byte[] data = new byte[ size]; int count = -1; while ((count = in.read(data, 0, size)) != -1) outStream.write(data, 0, count); data = null; int length = 0; return outStream.toByteArray();
}
}
//定义一个常量的类
public class Constants {
// File.separator类似和window的 “\”只是为了兼容Linux
public static final String VERSION_PATH= File.separator+“uploads”+File.separator+“upgrade”+File.separator;
}
//这是封装的一个文件上传的实体类
package com.xexun.vo;
import java.io.InputStream;
import java.io.Serializable;
public class FileInfo implements Serializable {
private String fileName;//上传文件的名称
private String contentType;//上传文件的类型
private Long fileSize;//文件的大小
private String parentPath;//存储文件父目录
private String relativePath;//相对路径
private String absolueBasePath;
private InputStream inputStream;//上传文件输入流
public FileInfo() {
}
public FileInfo(String fileName, String contentType, String parentPath, InputStream inputStream) {
this.fileName = fileName;
this.contentType = contentType;
this.parentPath = parentPath;
this.inputStream = inputStream;
}
public FileInfo(String fileName, String contentType, String parentPath, InputStream inputStream,String relativePath) {
this.fileName = fileName;
this.contentType = contentType;
this.parentPath = parentPath;
this.inputStream = inputStream;
this.relativePath = relativePath.replace("\\","/");
}
public FileInfo(String fileName, String contentType, Long fileSize, String parentPath, InputStream inputStream) {
this.fileName = fileName;
this.contentType = contentType;
this.fileSize=fileSize;
this.parentPath = parentPath;
this.inputStream = inputStream;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getContentType() {
return contentType;
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
public Long getFileSize() {
return fileSize;
}
public void setFileSize(Long fileSize) {
this.fileSize = fileSize;
}
public String getParentPath() {
return parentPath;
}
public void setParentPath(String parentPath) {
this.parentPath = parentPath;
}
public InputStream getInputStream() {
return inputStream;
}
public void setInputStream(InputStream inputStream) {
this.inputStream = inputStream;
}
public String getRelativePath() {
return relativePath;
}
public void setRelativePath(String relativePath) {
this.relativePath = relativePath;
}
public String getAbsolueBasePath() {
return absolueBasePath;
}
public void setAbsolueBasePath(String absolueBasePath) {
this.absolueBasePath = absolueBasePath;
}
}
//这里是一个文件上传工具类
package com.xexun.util;
import com.xexun.Constants;
import com.xexun.vo.FileInfo;
import it.sauronsoftware.jave.*;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;
import javax.imageio.ImageIO;
import java.awt.;
import java.awt.image.BufferedImage;
import java.io.;
import java.util.Calendar;
import java.util.Random;
/**
-
Created by lijunqi on 2015/6/4.
-
文件工具类
*/
public class FileUtil {
protected final transient Log log = LogFactory.getLog(getClass());/**
- 文件上传
- @param fileInfo
- @return 真实绝对路径
*/
public static String fileUpload(FileInfo fileInfo) {
String uploadPath = null;
try {
if (fileInfo != null) {
String fileName = fileInfo.getFileName();
String contentType = fileInfo.getContentType();
String parentPath = fileInfo.getParentPath();
InputStream is = fileInfo.getInputStream();
File file = new File(parentPath);
if (!file.exists()) {
file.mkdirs();
}
FileUtils.copyInputStreamToFile(is, new File(parentPath, fileName));
uploadPath = parentPath + “/” + fileName;
BufferedImage image = ImageIO.read(new File(uploadPath));
if (image == null) {
uploadPath = null;
}
}
} catch (Exception e) {
uploadPath = null;
e.printStackTrace();
}
return uploadPath;
}
/*
-
文件上传
/
public static String fileUploadPortrait(FileInfo fileInfo) {
String uploadPath = null;
try {
if (fileInfo != null) {
String fileName = fileInfo.getFileName();
String contentType = fileInfo.getContentType();
String parentPath = fileInfo.getParentPath();
InputStream is = fileInfo.getInputStream();
File file = new File(parentPath);
if (!file.exists()) {
file.mkdirs();
}
//fileName = String.valueOf(new Date().getTime())+fileName.substring(fileName.lastIndexOf("."));
FileUtils.copyInputStreamToFile(is, new File(parentPath, fileName));
uploadPath = fileInfo.getRelativePath() + “/” + fileName;
BufferedImage image = ImageIO.read(new File(parentPath + “/” + fileName));
if (image == null) {
uploadPath = null;
return uploadPath;
}
}
} catch (Exception e) {
uploadPath = null;
e.printStackTrace();
}
return uploadPath;
}
/* -
缩小并转换格式
-
@param fileInfo 源路径
-
@return
/
public static String narrowAndFormateTransfer(FileInfo fileInfo) {
String uploadPath = null;
try {
if (fileInfo != null) {
String fileName = fileInfo.getFileName();
String contentType = fileInfo.getContentType();
String parentPath = fileInfo.getParentPath();
InputStream is = fileInfo.getInputStream();
uploadPath = fileInfo.getRelativePath() + “/” + fileName;
/ int k=is.read();
if(k==-1){
return uploadPath;
}*/
File destFile = new File(parentPath, fileName);
if (!destFile.getParentFile().exists()) {
File parentFile = destFile.getParentFile();
parentFile.mkdirs();
}
BufferedImage src = ImageIO.read(fileInfo.getInputStream()); // 读入文件
if(src==null){
return uploadPath;
}
Image image = src.getScaledInstance(200, 200, Image.SCALE_DEFAULT);
BufferedImage tag = new BufferedImage(200, 200, BufferedImage.TYPE_INT_RGB);
Graphics g = tag.getGraphics();
g.drawImage(image, 0, 0, null); // 绘制缩小后的图
g.dispose();Boolean flag =ImageIO.write(tag, "jpg", new FileOutputStream(destFile));// 输出到文件流 if (!flag) { uploadPath = null; return uploadPath; } }
} catch (IOException e) {
e.printStackTrace();
}
return uploadPath;
}
/** -
缩小为长方形并转换格式
-
@param fileInfo 源路径
-
@return
/
public static String narrowAndFormateRectangleTransfer(FileInfo fileInfo) {
String uploadPath = null;
try {
if (fileInfo != null) {
String fileName = fileInfo.getFileName();
String contentType = fileInfo.getContentType();
String parentPath = fileInfo.getParentPath();
InputStream is = fileInfo.getInputStream();
uploadPath = fileInfo.getRelativePath() + “/” + fileName;
/ int k=is.read();
if(k==-1){
return uploadPath;
}*/
File destFile = new File(parentPath, fileName);
if (!destFile.getParentFile().exists()) {
File parentFile = destFile.getParentFile();
parentFile.mkdirs();
}
BufferedImage src = ImageIO.read(fileInfo.getInputStream()); // 读入文件
if(src==null){
return uploadPath;
}
Image image = src.getScaledInstance(220, 280, Image.SCALE_DEFAULT);
BufferedImage tag = new BufferedImage(220, 280, BufferedImage.TYPE_INT_RGB);
Graphics g = tag.getGraphics();
g.drawImage(image, 0, 0, null); // 绘制缩小后的图
g.dispose();Boolean flag =ImageIO.write(tag, "jpg", new FileOutputStream(destFile));// 输出到文件流 if (!flag) { uploadPath = null; return uploadPath; } }
} catch (IOException e) {
e.printStackTrace();
}
return uploadPath;
}
/** -
文件上传
*/
public static String fileUploadNoImg(FileInfo fileInfo) {
String uploadPath = null;
try {
if (fileInfo != null) {
String fileName = fileInfo.getFileName();
String contentType = fileInfo.getContentType();
String parentPath = fileInfo.getParentPath();
InputStream is = fileInfo.getInputStream();
File file = new File(parentPath);
if (!file.exists()) {
file.mkdirs();
}
FileUtils.copyInputStreamToFile(is, new File(parentPath, fileName));
uploadPath = parentPath + File.separator + fileName;
// String uploadPath2 = parentPath + File.separator +fileName.substring(0,fileName.lastIndexOf(".")+1)+“amr”;
//changeToAmr(uploadPath,uploadPath2);
return uploadPath;}
} catch (Exception e) {
uploadPath = null;
e.printStackTrace();
}
return uploadPath;
}
/**
- 保存语音文件
- @param fileCont 文件字节数组
- @param fileName 文件名称
- @param basePath 保存文件的根路径,绝对路径,一般是网站的根路径
- @param ext 扩展名
- @return
- @throws IOException
*/
public static String saveBytesToFile(byte[] fileCont, String fileName, String basePath, String ext) throws Exception {
FileOutputStream fos = null;
try {
String path = Constants.AUDIO_PATH + createCommPath(fileName) + “/”;
File file = new File(basePath + path);
if (!file.exists()) {
file.mkdirs();
}
String fileRelativePath = path + fileName + (ext == null ? “” : “.” + ext);
fos = new FileOutputStream(new File(basePath + fileRelativePath));
fos.write(fileCont);
fos.flush();
return fileRelativePath;
} catch (Exception e) {
throw e;
} finally {
if (fos != null) {
fos.close();
}
}
}
/**
- 按年月创建目录,并在其下平均分配100个文件夹来保存对应文件(如果文件足够多的话)
- @param commStr 一般是文件名
- @return
*/
private static String createCommPath(String commStr) {
StringBuffer sb = new StringBuffer();
Calendar calendar = Calendar.getInstance();
sb.append(calendar.get(Calendar.YEAR)).append(’/’).append(calendar.get(Calendar.MONTH)).append(’/’);
int hashCode;
if (StringUtils.isBlank(commStr)) {
hashCode = new Random().nextInt();
} else {
hashCode = commStr.hashCode();
}
int folderNum = Math.abs(hashCode % 100);
sb.append(folderNum);
return sb.toString();
}
public static void changeToAmr(String sourcePath, String targetPath) {
File source = new File(sourcePath);
File target = new File(targetPath);
AudioAttributes audio = new AudioAttributes();
audio.setCodec(“libamr_wb”);
audio.setBitRate(12200);
audio.setSamplingRate(8000);
audio.setChannels(1);
EncodingAttributes attrs = new EncodingAttributes();
attrs.setFormat(“amr”);
attrs.setAudioAttributes(audio);
Encoder encoder = new Encoder();
try {
encoder.encode(source, target, attrs);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InputFormatException e) {
e.printStackTrace();
} catch (EncoderException e) {
e.printStackTrace();
}
}public static void deleteFile(String sourcePath) {
File file = new File(sourcePath);
if (file.isFile() && file.exists()) {
file.delete();
}
}public static Boolean execute(File[] file1, String[] names, String strZipPath) {
deleteFile(strZipPath);
byte[] buffer = new byte[1024];
try {
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(
strZipPath));
for (int i = 0; i < file1.length; i++) {
FileInputStream fis = new FileInputStream(file1[i]);
out.putNextEntry(new ZipEntry(names == null ? file1[i].getName() : names[i]));
//设置压缩文件内的字符编码,不然会变成乱码
out.setEncoding(“GBK”);
int len;
// 读入需要下载的文件的内容,打包到zip文件
while ((len = fis.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
out.closeEntry();
fis.close();
}
out.close();
// this.downFile(getResponse(), tmpFileName);
} catch (Exception e) {
//log.error(“文件下载出错”, e);
return false;
}
return true;
}
}
package com.xexun.service.impl;
import com.xexun.dao.beetl.TermHttpVersionDaoBeetl;
import com.xexun.model.beetl.DictionaryData;
import com.xexun.model.beetl.TermHttpVersion;
import com.xexun.service.DictionaryBeetlManager;
import com.xexun.service.TermHttpVersionBeetlManager;
import org.beetl.sql.core.engine.PageQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;
/**
-
Attachment 管理service 层
*/
@SuppressWarnings(“ALL”)
@Service(“termHttpVersionBeetlManager”)
public class TermHttpVersionBeetlManagerImpl extends GenericBeetlManagerImpl<TermHttpVersion, Long> implements TermHttpVersionBeetlManager {@Resource
StringRedisTemplate stringRedisTemplate;
TermHttpVersionDaoBeetl termHttpVersionDaoBeetl;@Autowired
private DictionaryBeetlManager dictionaryBeetlManager;@Autowired
public TermHttpVersionBeetlManagerImpl(TermHttpVersionDaoBeetl termHttpVersionDaoBeetl) {
super(termHttpVersionDaoBeetl);
this.termHttpVersionDaoBeetl =termHttpVersionDaoBeetl;
}@Override
public void saveAndRedis(TermHttpVersion version, byte[] a) {
version=this.save(version);
new AsyncSaveVersion(version,a).start();
}
private class AsyncSaveVersion extends Thread {
private TermHttpVersion version;
private byte[] a;
public AsyncSaveVersion(TermHttpVersion version, byte[] a) {
this.version=version;
this.a=a;
}
@Override
public void run() {
long size= version.getVsSize();
long count=size%512>0?(size/512)+1:size/512;
stringRedisTemplate.opsForHash().put(“UPGRADE_VERSION”,version.getVsId()+"",count+"");
try {
byte[] pageCont=new byte[512];
int pageSzie=512;
for (int i=0;i<count;i++) {
if(i==count-1&&size%512>0){
pageSzie= (int) (size%512);
}
pageCont=new byte[pageSzie];
System.arraycopy(a,i*512,pageCont,0,pageSzie);
stringRedisTemplate.opsForHash().put(“UPGRADE_VERSION”,version.getVsId()+"_"+(i+1),new String(pageCont,“ISO-8859-1”));
}
} catch (IOException e) {
e.printStackTrace();
}
}}
}