文件上传

14 篇文章 0 订阅
13 篇文章 0 订阅

示例一:

【1】页面js:

/*
上传附件
docObj:文件对象
appid:cid
apptypeid:1、blog 2、
busitype:100——代表附件
*/
function uploadAttachment(docObj){
    var appid = $("#appid").val();
    var files =docObj.files;
    var formData = new FormData();//通过对象传输到后台
    formData.append("appid",appid);//用于sysfile插入数据的appid
    for (var i = files.length - 1; i >= 0; i--) {
        formData.append("files[]",files[i]);
    }
    $.ajax({
        data : formData,
        type : "POST",
        url : "/common/xxx/upload",
        cache : false,
        processData: false,                // jQuery不要去处理发送的数据
        contentType: false,                // jQuery不要去设置Content-Type请求头
        dataType: 'JSON',
        success: function(data) {//data是返回的hash,key之类的值,key是定义的文件名
            //查询
            $('#attachment').bootstrapTable('refresh');
            attachment(appid);
        },
        error:function(){
            toastr.error("上传失败");
        }
    });
}

【2】spring mvc后台接收多文件:

//下面新增自定义方法
@ResponseBody
@PostMapping("/upload")
R upload(@RequestParam("files[]") MultipartFile[] files,@RequestParam("appid") String appid) throws IOException, Exception {
	//多个附件上传
	for (int i = 0; i < files.length; i++) {
		System.out.println(i);
		String fname = files[i].getOriginalFilename();
//				String fileName = FileUtil.renameToUUID(fname);//换成uuid——也是唯一,好找图片
		String uuid = UUID.randomUUID().toString().replace("-", "");
		String fileType = fname.substring(fname.lastIndexOf(".") + 1, fname.length()).toLowerCase();
		String fileName = uuid+"."+fileType;//cf6ec8ccb62e451e8d5f27dab6bfeb3f.png
		FileUtil.uploadFile(files[i].getBytes(),tuodataConfig.getUploadPublicPath()+"blog/", fileName);
		FileDO fileDo= insertFile(appid,uuid,0,fname,fileName,fileType);
	}
	return R.ok();
}

示例二:

layui图片上传

【1】单张

html:
<body>
	<input type="hidden" name="rotationChartId" id="rotationChartId" value="#(rotationChart.id)" />
	<input type="hidden" name="mToken" value="#(mToken)" />

	<div class="layui-form-item">
		<label class="layui-form-label">轮播图片</label>
		<div class="layui-input-block">
			<input type="hidden" name="image" id="image" />
			<button type="button" class="layui-btn layui-btn-normal" id="chooseFile">选择文件</button>
			<div class="fileinput-new thumbnail" style="max-width: 200px; max-height: 150px;">
				<img #if(rotationChart.value==null) src="#(ctx)/assets/img/no.png" #else src="#(ctx)#(rotationChart.value)" #end id="demo1" />
			</div>
		</div>
	</div>
</body>


js:
新增的js脚本:
<script>
	layui.config({
		base: '#(ctx)/assets/layuiadmin/' //静态资源所在路径
	}).extend({
		index: 'lib/index' //主入口模块
	}).use(['index', 'form', 'laydate', 'upload'], function() {
		var $ = layui.$,
			admin = layui.admin,
			element = layui.element,
			layer = layui.layer,
			laydate = layui.laydate,
			form = layui.form,
			upload = layui.upload;

		// layui图片上传(单张)
		upload.render({
			elem: '#chooseFile',
			url: '#(curl)/rotationChartSave',
			auto: false,
			bindAction: '#submit', // 触发事件
			headers: {
				sessionId: '#(ac.sessionId)',
				menuId: '#(menuId)'
			},
			choose: function(obj) { //选择文件的回调,obj为选中的文件
				//将每次选择的文件追加到文件队列
				var files = obj.pushFile();

				//预览选中的文件(本地文件)
				obj.preview(function(index, file, result) {
					$('#demo1').attr('src', result);
				});
			},
			done: function(data) {
				if(data.code == 1) {
					window.location.reload();
				} else if(data.code == 2) {
					location.href = '#(ctx)/system/toLogin';
				}
				parent.layer.msg(data.desc, {
					offset: '80%'
				});
				layer.closeAll('loading');
			}
		});
	});
</script>

编辑的js脚本:
<script>
	layui.config({
		base: '#(ctx)/assets/layuiadmin/' //静态资源所在路径
	}).extend({
		index: 'lib/index' //主入口模块
	}).use(['index', 'form', 'laydate', 'upload'], function() {
		var $ = layui.$,
			admin = layui.admin,
			element = layui.element,
			layer = layui.layer,
			laydate = layui.laydate,
			form = layui.form,
			upload = layui.upload;
		
		// 通过formData进行传递数据
		var formData = new FormData($("#form")[0]);
		
		// layui图片上传(单张)
		upload.render({
			elem: '#chooseFile',
			url: '#(curl)/rotationChartUpdate',
			auto: false,
			bindAction: '#submit',
			data: {"rotationChartId":formData.get("rotationChartId")},// 通过属性进行获取值
			headers: {
				sessionId: '#(ac.sessionId)',
				menuId: '#(menuId)'
			},
			choose: function(obj) { //选择文件的回调,obj为选中的文件
				//将每次选择的文件追加到文件队列
				var files = obj.pushFile();

				//预览选中的文件(本地文件)
				obj.preview(function(index, file, result) {
					$('#demo1').attr('src', result);
				});
			},
			done: function(data) {
				if(data.code == 1) {
					window.location.reload();
				} else if(data.code == 2) {
					location.href = '#(ctx)/system/toLogin';
				}
				parent.layer.msg(data.desc, {
					offset: '80%'
				});
				layer.closeAll('loading');
			}
		});
	});
</script>

后台代码:
/**
 * 轮播图保存 
 */
@Before(value = { JMSystemApiInterceptor.class })
public void rotationChartSave() {
	String image = JMUploadKit.fileUpload(this, "file", "rotationChart");

	Configure rotationChart = new Configure();
	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	rotationChart.setValue2(sdf.format(new Date()));
	boolean result = false;
	if (image != null) {
		rotationChart.setName("rotationChart");
		rotationChart.setValue(image);
		result = configureDao.save(rotationChart);
	}
	if (result) {
		// 给type跟desc赋值
		Configure rotationChart1 = configureDao.get(false);
		rotationChart.setType(rotationChart1.getType() + 1);// 获取最后一个type
		rotationChart.setDesc("轮播图-" + (rotationChart1.getType() + 1));
		rotationChart.update();
		JMResult.success(this, "新增成功");
	} else {
		JMResult.fail(this, "新增失败");
	} 
}
/**
 * 轮播图更新 
 */
@Before(value = { JMSystemApiInterceptor.class })
public void rotationChartUpdate() {
	String image = JMUploadKit.fileUpload(this, "file", "rotationChart");
	Integer rotationChartId = getParaToInt("rotationChartId",null);
	Configure rotationChart = new Configure();
	
	Configure rotationChart1 = configureDao.getById(rotationChartId);
	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	boolean result = false;// 标识是否报错
	if (image != null) {
		if (rotationChart1.getValue() != null)
			ToolUpload.deleteFile(rotationChart1.getValue());
		rotationChart.setId(rotationChartId);
		rotationChart.setValue(image);
		rotationChart.setValue2(sdf.format(new Date()));// 记录更新时间
		result = configureDao.update(rotationChart);
	}
	if (result) {
		JMResult.success(this, "修改成功");
	} else {
		JMResult.fail(this, "修改失败");
	}
}

【2】多张

参考文章路径:https://www.layui.com/demo/upload.html

示例三

【1】oss上传图片

<c:set var="oss" value="https://wenbang.oss-cn-hangzhou.aliyuncs.com" />

<div class="form-group">
		<label class="control-label col-md-3">引导页</label>
		<div class="col-md-6">
			<div class="fileinput fileinput-new" data-provides="fileinput">
                                           <!--回显数据库图片-->
				<div class="fileinput-new thumbnail" style="max-width: 200px; max-height: 150px;">
					<img src="
						<c:if test="${ydy.value == null}">${ctx}/assets/global/img/no.png</c:if>
						<c:if test="${ydy.value != null}">${oss}${ydy.value}</c:if>" 
						alt="" />
				</div>
                                           <!--选择本地图片后回显-->
				<div class="fileinput-preview fileinput-exists thumbnail" style="max-width: 200px; max-height: 150px;"></div>
				<div>
					<span class="btn default btn-file"> 
						<span class="fileinput-new"> 选择图片 </span> 
						<span class="fileinput-exists"> 改变 </span> 
						<input type="file" name="image">
					</span> 
					<a href="javascript:;" class="btn red fileinput-exists" data-dismiss="fileinput"> 删除 </a>
				</div>
			</div>
			<div class="clearfix margin-top-10">
				<span class="label label-danger">NOTE!</span> 兼容 IE10+, FF3.6+, Safari6.0+, Chrome6.0+ and Opera11.1+.以上的浏览器
			</div>
		</div>
	</div>
后台代码:
String ossFileUpload = ToolUpload.OSSFileUpload(this, "image", "configure");
地址:wenbang/upload/configure/20190116/xxx.jpg
page 页面显示缩略图:
<td>
	<img src="<c:if test="${obj.value == null}">${ctx}/assets/global/img/no.png</c:if><c:if test="${obj.value != null}">${oss}${obj.value}</c:if>" style="max-width: 26px; max-height: 22px;">
</td>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

xuesibianxing

学有所沉,不忘初心,回馈社会

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值