版权声明:本文为HCG原创文章,未经博主允许不得转载。请联系[email protected] https://blog.csdn.net/qq_39455116/article/details/82379331
JS代码:
<script>
$(function(){
var oFileInput = $("#fileInput"); //选择文件按钮
var oFileBtn = $("#fileBtn"); //上传按钮
var flieList = []; //数据,为一个复合数组
var sizeObj = []; //存放每个文件大小的数组,用来比较去重
//点击选择文件按钮选文件
oFileInput.on("change",function(){
analysisList(this.files);
})
//解析列表函数
function analysisList(obj){
//如果没有文件
if( obj.length<1 ){
return false;
}
for( var i=0;i<obj.length;i++ ){
var fileObj = obj[i]; //单个文件
var name = fileObj.name; //文件名
var size = fileObj.size; //文件大小
var type = fileType(name); //文件类型,获取的是文件的后缀
//文件类型不为这三种,就不上传
if( ("txt").indexOf(type) == -1 ){
$('.error').text('“'+ name +'”文件类型不对,不能上传');
$('.error').css("color","red");
continue;
}
//文件大于30M,就不上传
if( size > 1024*1024*500 || size == 0 ){
$('.error').text('“'+ name +'”超过了500M,不能上传');
$('.error').css("color","red");
continue;
}
//把文件大小放到一个数组中,然后再去比较,如果有比较上的,就认为重复了,不能上传
if( sizeObj.indexOf(size) != -1 ){
$('.error').text('“'+ name +'”已经选择,不能重复上传');
$('.error').css("color","red");
continue;
}
$('.error').text('');
var itemArr = [fileObj,name,size,type]; //文件,文件名,文件大小,文件类型
flieList = [];
flieList.push(itemArr);
var fileData = flieList[0]; //flieList数组中的某一个
$("#fileName").val("");
$("#fileName").val(fileData[1]);
}
};
//上传
oFileBtn.on("click",function(){
var fileName = $('#fileName').val('');
if("" == fileName){
return;
}
uploadFn();
function uploadFn(){
debugger
var formData = new FormData();
var arrNow = flieList[0]; //获取数据数组的当前项
if(undefined != arrNow){
// 从当前项中获取上传文件,放到 formData对象里面,formData参数以key name的方式
var result = arrNow[0]; //数据
formData.append("originMaterial" , result);
$.ajax({
type: "post",
dataType: 'json',
data: formData,
processData: false,
contentType: false,
async: false,
url: '/td/datacube/dmpTagsUpload/uploadFile',
success: function (result) {
if("1" == result.flag){
$('.error').text('上传成功');
$('.error').css("color","green");
$('#fileName').val('');
}
},
error: function (result) {
$('.error').text('系统错误,请重新上传');
}
});
}else{
$('.error').text('请选择文件上传');
}
}
});
})
//通过文件名,返回文件的后缀名
function fileType(name){
var nameArr = name.split(".");
return nameArr[nameArr.length-1].toLowerCase();
}
</script>
java代码
@RequestMapping("uploadFile")
@ResponseBody
public Map<String,Object> uploadFile(@RequestParam("originMaterial") MultipartFile multipartFile, HttpServletRequest request){
HttpSession session = request.getSession();
UserDO sessionUser = (UserDO)session.getAttribute("user");
Map<String,Object> resultMap = new HashMap<String,Object>();
//文件名称
String fileName = multipartFile.getOriginalFilename();
try {
InputStream fileInputStream = multipartFile.getInputStream();
//保存到服务器的路径
SaveFileFromInputStream(multipartFile.getInputStream(), ReadPropertiesUtil.readDmpAddress(),fileName);
DmpTagsUploadDO dmpTagsUploadDO = new DmpTagsUploadDO();
dmpTagsUploadDO.setFileName(fileName);
dmpTagsUploadDO.setUserId(String.valueOf(sessionUser.getId()));
int result = dmpTagsUploadService.addDmpTagsUpload(dmpTagsUploadDO);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
resultMap.put("flag","1");
return resultMap;
}
控制层调用的SaveFileFromInputStream()方法
/**
* 将MultipartFile转化为file并保存到服务器上的某地
*/
public void SaveFileFromInputStream(InputStream stream,String path,String savefile) throws IOException
{
FileOutputStream fs=new FileOutputStream( path + File.separator + savefile);
byte[] buffer =new byte[1024*1024];
int bytesum = 0;
int byteread = 0;
while ((byteread=stream.read(buffer))!=-1)
{
bytesum+=byteread;
fs.write(buffer,0,byteread);
fs.flush();
}
fs.close();
stream.close();
}
其中ReadPropertiesUtil.readDmpAddress()用的就是下面读取配置文件类里面的参数
message.properties内容
#本地
dmp.message.url=D:/temp
#线上
#dmp.message.url=/data/project/datacube
公共类
package com.ybl.td.util;
import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;
/**
* @author huihui
* @create 2018-01-31 11:26
* @desc 读取配置文件properties的类
**/
public class ReadPropertiesUtil {
private static Properties properties = null;
private static Properties messageProperties = null;
private static final String message = "message.properties";
static {
try {
properties = new Properties();
File file = ResourceFileUtil.getResourceFile("properties/userDefinedEnvConfig.properties");
if( null != file){
FileInputStream fileInputStream = new FileInputStream(file);
properties.load(fileInputStream);
}
}catch (Exception e){
e.printStackTrace();
}
}
public static String readFilePath() {
return properties.getProperty("td.upload.fileUpload");
}
public static String readAuditPath() {
String domain = properties.getProperty("td.audit.domain");
String path = properties.getProperty("td.audit.path");
return domain+path;
}
public static String readMailLogo() {
return properties.getProperty("logoUtl");
}
public static String readDmpAddress(){
try {
messageProperties = new Properties();
File file = ResourceFileUtil.getResourceFile(message);
if( null != file){
FileInputStream fileInputStream = new FileInputStream(file);
properties.load(fileInputStream);
}
}catch (Exception e){
e.printStackTrace();
}
String dmpSaveUrl = properties.getProperty("dmp.message.url");
return dmpSaveUrl;
}
}