HTTP上传 文件上传 图片上传 HTTP上传原理 文件上传原理 图片上传原理

1.概述

在最初的http协议中,没有上传文件方面的功能。rfc1867(http://www.ietf.org/rfc/rfc1867.txt )为http协议添加了这个功能。浏览器按照此规范将用户指定的文件发送到服务器。服务器再按照此规范,解析出文件。大部分的http server都支持此协议,比如tomcat(本文用的是Spring MVC,即HttpServelet来接收请求)。

网上很多博客,以及插件的做法,是建一个iframe用户无刷新请求,再建一个form用于提交。但其实可以直接用JavaScript和ajax提交。


2.前端实现

首先,需要type为file的input标签,该标签用于选择文件,手机和PC都适用。
然后,当你点击file input标签的时候,会弹出选择文件控件(该控件是操作系统内部提供的)
最后,就是提交form(form的enctype必须为“multipart/form-data”),提交form的目的是把file input里面的文件提交给服务器。用一个submit按钮提交form。

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=0">
</head>
<body>
<form name="myform" enctype="multipart/form-data" action="http://localhost/uploadImage" method=post>
<input name="userfile1" type="file" onchange="upload(this);">
</form>
</body>
<script>
function upload() {
var myform = document.forms['myform'];
myform.method = 'POST';
myform.submit();
}
</script>
</html>

 

3.后端实现

 @RequestMapping(value = "/uploadImage")
    @ResponseBody
    public String uploadImage(HttpServletRequest request) throws IOException {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest)request;
        Iterator<String> iterator = multipartRequest.getFileNames();
        String fileName = "";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String dir = "upload/" + sdf.format(new Date()) + "/";
        String realPath = request.getSession().getServletContext().getRealPath("/");
        while(iterator.hasNext()){
            MultipartFile multipartFile = multipartRequest.getFile(iterator.next());
            if(multipartFile != null){
                String fn = multipartFile.getOriginalFilename();
                String suffix = fn.substring(fn.lastIndexOf("."));
                fileName = dir  + Utils.getRandomStringByLength(6) + suffix;
                String path = realPath + fileName;
                path = path.replace("\\", "/");
                File f = new File(path);
                if(!f.mkdirs()){
                    f.mkdir();
                }
                multipartFile.transferTo(f);
            }
        }
        return fileName;
    }



 

转载于:https://www.cnblogs.com/tonyzeng/p/5583199.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值