WebMVC上传文件

原创
2020/01/08 09:04
阅读数 664

 

 

web前端

<!DOCTYPE html>
<html lang="zh-CN">

<head>
	<meta charset="UTF-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<link rel="stylesheet" href="__APP__/assets/css/layui.css">
	<script src="__APP__/assets/js/jquery-1.11.0.min.js"></script>
	<script src="__APP__/assets/layui.all.js"></script>
	<title>WebMVC</title>
</head>

<body style="background-color: #F2F2F2">


	<form class="layui-form">
				<div class="layui-form-item">
						<label class="layui-form-label"><span class="bitian">*</span>头像</label>
						<div class="layui-upload">
							<button type="button" class="layui-btn" id="test1">上传图片</button>
							<div class="layui-upload-list">
								<img class="layui-upload-img" id="demo1">
								<p id="demoText"></p>
							</div>
						</div>
					</div>	

	</form>
	<script>
		
layui.use(['form','upload'], function() {
	var form=layui.form;
	var upload = layui.upload;
	var uploadInst = upload.render({
		elem: '#test1'
		,url: 'upimage'
		,before: function(obj){
		  //预读本地文件示例,不支持ie8
		  obj.preview(function(index, file, result){
			$('#demo1').attr('src', result); //图片链接(base64)
		  });
		}
		,done: function(res){
		  //如果上传失败
		  if(res.code != 0){
			return layer.msg('上传失败');
		  }
		  //上传成功
		}
		,error: function(){
		  //演示失败状态,并实现重传
		  var demoText = $('#demoText');
		  demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
		  demoText.find('.demo-reload').on('click', function(){
			uploadInst.upload();
		  });
		}
	  });	
	  form.render();
});
	</script>
</body>


</html>
后端
procedure TIndexController.upimage;
var
  FFileName, nFileName, s: string;
  AFile: TFileStream;
  ret: ISuperObject;
  k: integer;
  path: string;
begin
  with view do
  begin
    k := Request.Files.Count - 1;
    if k > -1 then
    begin
      path := AppPath + 'upfile';
      if not DirectoryExists(path) then
      begin
        CreateDir(path);
      end;
      s := ExtractFileName(Request.Files[k].FileName);
      FFileName := path + '\' + Plugin.Tool.GetGUID + copy(s, Pos('.', s), s.Length - pos('.', s) + 1);
      AFile := TFileStream.Create(FFileName, fmCreate);
      try
        Request.Files[k].Stream.Position := 0;
        AFile.CopyFrom(Request.Files[k].Stream, Request.Files[k].Stream.Size);  //测试保存文件,通过。
      finally
        AFile.Free;
      end;
      ret := SO();
      ret.I['code'] := 0;
      ret.S['message'] := '上传完毕';
    end
    else
    begin
      ret := SO();
      ret.I['code'] := -1;
      ret.S['message'] := '上传失败';
    end;
    ShowJSON(ret);
  end;
end;

 

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部