Java上传文件Demo

Java上传文件Demo,第1张

首先需要创建一个模态框来选择文件。

<div class="modal fade" id="uploadOtherFileModal" tabindex="-1" role="dialog" aria-labelledby="uploadOtherFileModal" aria-hidden="true">
	<div class="modal-dialog">
		<div class="modal-content">
			<div class="modal-header">
				<h1 class="modal-title">
                    	请选择上传的附件
                h1>
			div>
			<div class="modal-body">
				<div class="form-group">
					<form enctype="multipart/form-data">
						<input type="file" name="file" id="uploadOtherFile"/><br/>
					form>				
				div>
			div>
			<div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭
                button>
                <button type="button" class="btn btn-primary" id="uploadOtherFileConfirm">
                    	确定
                button>
            div>
		div>
	div>
div>
js控制模态框的显示与关闭,并获取到文件发送ajax请求。
//上传附件模态框显示
$("body").on("click",".CF16",function(){
	$("#uploadOtherFileModal").modal("show");
});

//上传文件
$('#uploadOtherFileConfirm').click(function () {
	var file = $('#uploadOtherFile')[0].files[0];
	if (file==null) {
		alert("请选择文件");
		return;
	}

	var formData = new FormData();    
	formData.append("MKDM", MKDM);
	formData.append("YWBH", YWBH);
	formData.append("YWLSH", YWLSH);
	formData.append("OtherFiles", file);

	$.ajax({
		url:"../../upload/uploadOtherFile.do",
		type:'POST',
		async: false,
		data: formData,
		dataType:'json',
		cache: false, // 上传文件无需缓存
		processData : false, // 使数据不做处理
		contentType : false, // 不要设置Content-Type请求头
		success: function(data){
			console.log(data);

			if (data.res == "1") {
				alert('上传成功!');
				$("#uploadOtherFileModal").modal("hide");
			}else{
				alert(data.msg+":"+data.data);
			}

		},
		error:function(response){
			console.log(response);
		}
	});
})

效果图:

3. 后端处理获取文件名以及文件加密为字符串

@Controller
@RequestMapping("/upload")
public class UploadController {

	private static  LogUtilities logger;
	static {
		logger = new LogUtilities();
	}
	
	@Autowired
	InvoiceDao invoiceDao;
	
	@ResponseBody
	@RequestMapping(value = "uploadOtherFile", method = RequestMethod.POST)
	public Object uploadOtherFile(
			@RequestParam("MKDM") String MKDM,
            @RequestParam("YWBH") String YWBH,
            @RequestParam("YWLSH") String YWLSH,
            @RequestPart("OtherFiles") MultipartFile OtherFiles){
		
		logger.info("uploadOtherFile请求获取的 MKDM:"+MKDM+",YWBH:"+YWBH+",YWLSH:"+YWLSH);
				
		String fileName = OtherFiles.getOriginalFilename().substring(0, OtherFiles.getOriginalFilename().lastIndexOf("."));
		logger.info("上传的附件的文件名:"+fileName);
		
		if (OtherFiles == null || OtherFiles.isEmpty()) {
            throw new RuntimeException("附件不能为空!");
        }
		byte[] fileBytes = null;
		String OtherFilesOfBase64="";
		try{
			fileBytes = OtherFiles.getBytes();
			BASE64Encoder base64Encoder =new BASE64Encoder();
			OtherFilesOfBase64=base64Encoder.encode(fileBytes);
			OtherFilesOfBase64=OtherFilesOfBase64.replaceAll("[\s*\t\n\r]", "");
			logger.info("通过Base64加密后的文件字符串:"+OtherFilesOfBase64);
		}catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		List<ApprovalStatus> approvalStatusList=invoiceDao.queryApprovalStatus(MKDM,YWBH,YWLSH);
		String postUrl=approvalStatusList.get(0).getCF5();
		String agreeStatus =approvalStatusList.get(0).getSPZT();
		logger.info("SPZT.CF5字段的Post回写地址:"+postUrl);
		logger.info("审批结果为:"+agreeStatus);
		
		if(StringUtils.isEmpty(postUrl)){
			return new ResultResp("1","失败","SPZT.CF5字段的Post回写地址为空");
		}else{
			JSONObject postData = new JSONObject();
			postData.put("mkdm",MKDM);
			postData.put("ywbh",MKDM);
			postData.put("ywlsh",MKDM);
			postData.put("spjg",agreeStatus);
			postData.put("method","4");
			postData.put("wjm",fileName);
			postData.put("fjnr",OtherFilesOfBase64);
			logger.info("发送http请求请求参数为:"+postData.toString());
			String resultTokenStr = HttpUtils.doPostBodyByJson(postUrl, postData, "UTF-8");
			logger.info("发送请求结束获取的返回值:"+resultTokenStr);
			return resultTokenStr;
		}
	}
}

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/1320204.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-11
下一篇2022-06-11

发表评论

登录后才能评论

评论列表(0条)

    保存