首页 新闻 搜索 专区 学院

哪位兄弟做过MVC的上传文件功能,能否教下我╮(╯_╰)╭。

0
[已解决问题] 解决于 2017-06-29 16:58

前台

<form action="/" method="post" enctype="multipart/form-data">
  <input type="text" class="file" id="f_file"> <input id="sdsds" type="button" value="上传文件" onclick="t_file.click()" onmouseover="fclick(t_file)">
  <input name="t_file" type="file" id="t_file" onchange="f_file.value=this.value" style="display:none">
  <br/>
  <input id="input_submit" type="submit" value="提交">
</form>

javascript:这个是百度的,我也不太看得懂,咋们尽量用jquery,别用原生代码

function fclick() {
    with (obj) {
         style.posTop = event.srcElement.offsetTop
         var x = event.x - offsetWidth / 2
         if (x < event.srcElement.offsetLeft) x = event.srcElement.offsetLeft
         if (x > event.srcElement.offsetLeft + event.srcElement.offsetWidth - offsetWidth) x = event.srcElement.offsetLeft + event.srcElement.offsetWidth - offsetWidth
            style.posLeft = x
        }
    }

 

效果

后台

复制代码
public ActionResult CreateExchange(string Submit)
        {
            HttpPostedFileBase file = Request.Files["t_file"];
            if (file != null && file.Equals(""))
            {
                try
                {
                    string strFilPath = Path.Combine(HttpContext.Server.MapPath("~/Upload"), Path.GetFileName(file.FileName));
                    file.SaveAs(strFilPath);
                    return RedirectToAction("CreateExchange", "HomePage");
                }
                catch
                {
                    return Content("上传异常 !", "text/plain");
                }
            }
            return View();
        }
复制代码

 讲下需求哈。

1.点击“提示”非空验证。

2.提交功能正常,附件上传成功。

3.发布成功。

对了,我是柔弱的妹子,刚接触MVC,一点都不懂,求个哥哥姐姐帮忙教下,没办法这时候必须装下,博取好感嘛。

你猜丶的主页 你猜丶 | 菜鸟二级 | 园豆:210
提问于:2017-03-28 14:06
< >
分享
最佳答案
0

前台代码 :

 <form id="importForm" action="url" 
                method="post" enctype="multipart/form-data" 
                class="form-horizontal"
                onsubmit="loading('正在导入,请稍等...');">
                
                <br />
                <div class="form-group">
                    <label class="control-label col-xs-12 col-sm-2 no-padding-right"
                    for="choose_custNo">选择材料:<span style="color:red;vertical-align:middle;">*</span></label>
                    <div class="col-xs-12 col-sm-8">
                    <input id="uploadFile" name="file" type="file"
                    style="width:330px" />
                </div>    
                </div> 
                 
            
                 <input id="btnImportSubmit"
                    class="btn btn-primary" type="submit"  value="上传" /> 
                
            </form> 

后台代码 :

   @RequestMapping(value = "import", method = RequestMethod.POST,produces = "text/html;charset=UTF-8")
    @ResponseBody
    public  String saveUpload(@RequestParam(required = false)MultipartFile file,
            HttpServletRequest request,HttpServletResponse response,
            Model model, RedirectAttributes redirectAttributes) {
     JSONObject json = new JSONObject();
        Map<String, Object> returnMap = Maps.newHashMap();
        long z = file.getSize();
     if(file.getSize() != 0){
      //文件名
                String fileName = file.getOriginalFilename();
                
                String sername="";
                String path = "";
                //后缀
                String prefix=fileName.substring(fileName.lastIndexOf(".")+1);
                
                DateFormat df= new SimpleDateFormat("yyyyMMdd");
                String dirs=df.format(new Date());
                
                String filePath = request.getSession().getServletContext().getRealPath("/")+"/upload/"+"/名字/"          +dirs;

        File file2 = new File(filePath, fileName);
        if(!file2.getParentFile().exists()){
                file2.getParentFile().mkdirs();
                }
                if(!file2.exists()){
                file2.createNewFile();
                 sername = file2.getName();
                 path = file2.getPath();
                }else{
                    //获取重命名后的文件名
                    file2.renameTo(new File(filePath, System.currentTimeMillis() + fileName));
                     sername = System.currentTimeMillis() + fileName;
                     File file3 = new File(filePath, sername);
                     path =file3.getAbsolutePath(); 
                }
                /**/
                file.transferTo(file2);
     if(result==1){
            json.put("isSuccess", true);
               json.put("msg", "添加成功");
        }else{
             json.put("isSuccess", true);
                json.put("msg", "添加失败");
        }
        CommonFunctionUtil.operateDB(returnMap, result);
        return json.toString();
}

}

 

jquery:

$("#btnImportSubmit").click(function () {     
$('#importForm').form('submit', {
   url:"${ctx}/business/rule1/businessprecensor/bsBusinessPrecensor/import",
   success:function(data){
    var msg = eval('(' + data + ')');
    if (msg.msg=="添加成功") {
      alert("添加成功");
    }
} }); });
奖励园豆:5
无殇-x | 初学一级 |园豆:4 | 2017-03-28 17:01
其他回答(3)
1

 可以用ajaxform,注意先要引用jquery.js,再引用jquery.form.js ,js是返回json的例子,可以对options的datatype进行更改为text/plain

 

var options = {
beforeSubmit: showRequest, //提交前处理
success: showResponse, //处理完成
resetForm: true,
dataType: 'json',
type: 'post'
};



//这里用form-uploadfile是form的id

$('#form-uploadfile').submit(function () { //注意这里的index_form
$(this).ajaxSubmit(options);
return false;//防止dialog 自动关闭
});



//这里可以对请求前的参数进行处理

function showRequest(formData, jqForm, options) {
var queryString = $.param(formData);

return true;
}



//这里对请求完成后进行处理,可以弹出提示信息之类的,responseText是返回的数据
function showResponse(responseText, statusText, xhr, $form) {

if (responseText.success) {

return true;
}
else {
alert(responseText.msg);
return false;
}

}

 

 

后端类似这样

[HttpPost]
    public ActionResult Upload(TestModel tm, HttpPostedFileBase file)
    {
        if (file == null)
        {
            return Content("没有文件!", "text/plain");
        }
        var fileName = Path.Combine(Request.MapPath("~/Upload"), Path.GetFileName(file.FileName));
        try
        {
            file.SaveAs(fileName);
            //tm.AttachmentPath = fileName;//得到全部model信息
            tm.AttachmentPath = "../upload/" + Path.GetFileName(file.FileName);
          //return Content("上传成功!", "text/plain");
            return RedirectToAction("Show",tm);
        }
        catch
        {
            return Content("上传异常 !", "text/plain");
        }
    }

 

ldybyz | 园豆:138 (初学一级) | 2017-03-28 14:40

好像不能引用jquery.js,再引用jquery.form.js,会影响其他功能

支持(0) 反对(0) 你猜丶 | 园豆:210 (菜鸟二级) | 2017-03-28 15:17

@你猜丶: 

 

可能也有兼容性问题,可以试一下,需要jquery,这里就不用form表单提交了,注意看提示

//按钮类型不要用submit,
 //data.append("file", files[0]);中的file是后台HttpPostedFileBase对象 的名称

//xhr是返回的数据

$('#input_submit').on('click', function () {
        var data = new FormData();
        var files = $("#f_file").get(0).files;
        if (files.length > 0) {
            data.append("file", files[0]);
        }

        var ajaxRequest = $.ajax({
            type: "POST",
            url: "/File/Upload",
            contentType: false,
            processData: false,
            data: data
        });
        ajaxRequest.done(function (xhr, textStatus) {

            alert(xhr);
        });
    });
支持(0) 反对(0) ldybyz | 园豆:138 (初学一级) | 2017-03-28 16:13
0

思路:

首先采用 form提交,如果觉得其他复杂的话。

1.新建2个View(success page 和failed page)

2.在出发提交事件前--非空验证。

if ($('#videoUploadFile').get(0).files.length === 0) { console.log("No files selected."); }

3.后台获取文件。

public ActionResult UploadFile(HttpPostedFileBase file)

{

  //设置文件存储路径

  //保存文件

  // 根据结果返回对应的View

  //success or failed page

}

肖恩部落 | 园豆:575 (小虾三级) | 2017-03-28 14:54
0

我倒是有个,原生的上传下载图片的 可以修改成上传下载文件

 var uploadInfo = {};
        //遍历绑定 文件改变事件
        var allImg = $("input");
        $.each(allImg, function (index, item) {
            item.addEventListener("change", getPic, false);
        })

        function getPic(evt) {
            /// <summary>监听图片上传事件</summary>
            var imgID = this.title;
            var getImg = document.getElementById("img_" + imgID);
            var uploadingImg = document.getElementById("uploadingImg");
            var file = evt.dataTransfer !== undefined ? evt.dataTransfer.files[0] : evt.target.files[0];
            uploadInfo.type = file.type;
            uploadInfo.name = file.name;
            //图片格式验证
            if (!file.type.match(/image.*/)) { return; }

            var reader = new FileReader();
            reader.onload = (function () {
                return function (e) {
                    uploadInfo.imageBase64 = e.target.result;
                    uploadingImg.src = event.target.result;
                    getImg.style.backgroundImage = "url('" + event.target.result + "')";
                    var uploadImg = picCompress(uploadingImg, 50);

                    if (!uploadImg) {
                        return;
                    }
                    var resImg = uploadImg.toString().split("base64,")[1];
                    hm.getJSON("@Url.Action("UploadFileImg", "File")", { strBase64: resImg }, function (data) {
                        if (data.HasError) {
                            hm.showMsg(data.Message, "提示", "msg", {
                                "确定": function () {
                                    return;
                                }
                            });
                            return;
                        } else {
                            var comData = data.ComData;
                            if (comData && comData != "undefined") {
                                /*上传成功之后存进session隐藏上传按钮并提示上传成功*/
                                sessionStorage["ptrade-realaffirm-pic" + imgID] = comData;
                                document.getElementById("pic" + imgID).style.display = "none";
                                document.getElementById("uploadArea" + imgID).className = "hy-icon hy-icon-true";
                                document.getElementById("txtpic" + imgID).innerText = "上传成功!";
                                document.getElementById("img_" + imgID).addEventListener("click", showLargerImg, false);
                            }
                        }
                    });
                }
            })(file);
            reader.readAsDataURL(file);
        }
    })

    function picCompress(img, quality, output_format) {
        /// <summary>压缩图片并获取图片Base64编码</summary>
        /* MIME type,表示数据呈现的格式,即指定嵌入数据的MIME。对于PNG的图片,其格式是:image/png,如果没有指定,默认是:text/plain;*/
        var mime_type = "image/jpg";
        if (output_format != undefined && output_format == "png") {
            mime_type = "image/png";
        }
        var cvs = document.createElement('canvas');
        cvs.width = img.naturalWidth;
        cvs.height = img.naturalHeight;
        //图片压缩
        var ctx = cvs.getContext('2d').drawImage(img, 0, 0);
        //获取图片Base64编码
        var newImgData = cvs.toDataURL(mime_type, quality / 100);
        var retImg = newImgData;
        return retImg;
    }

    function checkPic() {
        /// <summary>检查图片信息确定上传成功后跳转</summary>
        var img_1 = sessionStorage["ptrade-realaffirm-pic1"],
            img_2 = sessionStorage["ptrade-realaffirm-pic2"],
            img_3 = sessionStorage["ptrade-realaffirm-pic3"];
        if (img_1 && img_2 && img_3 && img_1 != "undefined" && img_2 != "undefined" && img_3 != "undefined") {
            window.location = "@Url.Action("RealNameAuthentication", "Reality")";
        }
    }
    function showLargerImg() {
        var myMask = document.getElementById("myMask"),
            myDialog = document.getElementById("myDialog"),
            largerImg = document.getElementById("largerImg");
        myMask.style.display = "block";
        myDialog.style.display = "block";
        var imgUrl = this.style.backgroundImage;
        imgUrl = imgUrl.replace("url(\"", "").replace("\")", "");
        largerImg.src = imgUrl;
    }
流年过往 | 园豆:464 (菜鸟二级) | 2017-03-30 10:08
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册