springboot中Ajax上传文件

1.application.properties 配置文件中添加

#上传地址
upload.file=d:\\upload\\test\\
#上传以后预览地址
file.url=http://192.168.1.66/pre_file/

2.前端页面,

1.引入以下js
<script type="text/javascript" th:src="@{/jquery/1.9.1/jquery.min.js"></script>

<script type="text/javascript" th:src="@{/jquery.upload/jquery.upload-1.0.2.js"></script>

<script type="text/javascript" th:src="@{/lib/layer/2.4/layer.js}"></script>

2.input name和Controller类中的名字一样
<input type="file" multiple="multiple" id="file" name="file" class="input-file" />

3.js部分
$(function(){
	$("input[type=file]").change(function(){
		uploadImage(this.id);
	});
	
});
/* 图片-上传 */
function uploadImage(fileid) {
	
	var upfile = $("#"+fileid);
	var filepath = upfile.val();
	if (filepath == '') {
		layer.msg('请选择文件!', {
			icon : 5,
			time : 1000
		});
		return false;
	}

	var fileName = filepath.substring(filepath.lastIndexOf("\\") + 1,
			filepath.length);
	resName = fileName;
	// 文件名
	var fileType = fileName.substring(fileName.indexOf(".") + 1,fileName.length);
	if (fileType == 'exe') {
		layer.msg('请上传合适类型的文件!', {
			icon : 2,
			time : 2000
		});
		return false;
	}
	var index = layer.msg('加载中...', {
		icon : 16,
		shade : 0.2,
		time : 0
	});
	var param = {
			fileName:fileName,
			languageType:$('#sel_languageType').val()
	};
	
	$("#"+fileid).upload('/back/testAction',param, function(data) {
		layer.close(index);
		if (data.status) {
			layer.msg("导入成功了!",{icon:6,time:1000});
		} else {
			layer.msg(data.message, {icon:2,time:10000});
		}
	}, 'json');
}

3.Controller类

@Controller
@RequestMapping("/back/test")
@ResponseBody
public class SystemController{
 
    
    // 文件上传路径
    @Value("${upload.file}")
    private String fileUploadPath;
    // 文件访问路径
    @Value("${file.url}")
    private String filePre;

    @RequestMapping("test")
    public PageModule test(HttpServletRequest request,MultipartFile file,String languageType){
        PageModule module = new PageModule();
        
        String userCode = getUserCode(request);
        String filePath = FileUploadUtil.singleFileUpload(file,
                fileUploadPath, filePre);
        
        return module;
    }

}

4.用到的公共上传类

/**
 * Project Name
 * File Name:FileUploadUtil.java
 * Package Name:com.lkx.util
 * Date:2017年3月2日下午7:37:12
 * Copyright (c) 2017~2020, likaixuan
 *
*/


import java.io.File;
import java.io.IOException;

import org.springframework.web.multipart.MultipartFile;



/**
 * ClassName:FileUploadUtil Function: TODO ADD FUNCTION. Reason: TODO ADD
 * REASON. Date: 2017年3月2日 下午7:37:12
 * 
 * @author likaixuan
 * @version V1.0
 * @since JDK 1.7
 * @see
 */
public class FileUploadUtil {
    
    private static final String SEPARATOR = "/";

    /**
     * singleFileUpload:(单个文件上传) 
     * TODO(返回文件上传后所在路径) 
     * 
     * @return fileurl
     * @since JDK 1.7
     */
    public static String singleFileUpload(MultipartFile file,String savePath,String prePath) {
        String filePath = "";// 文件上传后,可访问的路径
        try {
            //判断savePath路径最后是否带/,如果不带追加
            String lastStr = savePath.substring(savePath.length()-2);
            if(lastStr.contains("/")){
                filePath = savePath + DateUtil.getNowYearMoth() + SEPARATOR
                        + file.getOriginalFilename();
            }else{
                savePath+=SEPARATOR;
                filePath = savePath +SEPARATOR+ DateUtil.getNowYearMoth() + SEPARATOR
                        + file.getOriginalFilename();
            }
            
            // 前端传入mulFileSource
            // 创建压缩前源文件
            File fileSourcePath = new File(savePath + DateUtil.getNowYearMoth());
            File fileSource = new File(fileSourcePath, file.getOriginalFilename());
            if (!fileSourcePath.exists()) {
                fileSourcePath.mkdirs();
            }
            file.transferTo(fileSource);
        } catch (IllegalStateException e) {
            throw new RuntimeException();
        } catch (IOException e) {
            throw new RuntimeException();
        }
        return savePath+ DateUtil.getNowYearMoth() + SEPARATOR
                + file.getOriginalFilename();
        //return prePath+SEPARATOR+DateUtil.getNowYearMoth()+SEPARATOR+file.getOriginalFilename();
    }
    
    
    /**
     * singleFileUpload2:(单个文件上传) 
     * TODO(返回文件上传后网络访问路径) 
     * 
     * @return fileurl
     * @since JDK 1.7
     */
    public static String singleFileUpload2(MultipartFile file,String savePath,String prePath) {
        String filePath = "";// 文件上传后,可访问的路径
        try {
            //判断savePath路径最后是否带/,如果不带追加
            String lastStr = savePath.substring(savePath.length()-2);
            if(lastStr.contains("/")){
                filePath = savePath + DateUtil.getNowYearMoth() + SEPARATOR
                        + file.getOriginalFilename();
            }else{
                savePath+=SEPARATOR;
                filePath = savePath +SEPARATOR+ DateUtil.getNowYearMoth() + SEPARATOR
                        + file.getOriginalFilename();
            }
            String contentType = file.getContentType();
            System.out.println("likaixan:"+contentType);
            
            // 前端传入mulFileSource
            // 创建压缩前源文件
            File fileSourcePath = new File(savePath + DateUtil.getNowYearMoth());
            File fileSource = new File(fileSourcePath, file.getOriginalFilename());
            if (!fileSourcePath.exists()) {
                fileSourcePath.mkdirs();
            }
            file.transferTo(fileSource);
        } catch (IllegalStateException e) {
            throw new RuntimeException();
        } catch (IOException e) {
            throw new RuntimeException();
        }
        return prePath+SEPARATOR+DateUtil.getNowYearMoth()+SEPARATOR+file.getOriginalFilename();
    }
    
    

}

 

转载于:https://my.oschina.net/likaixuan0/blog/1503952

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值