【问题标题】:How To Upload Image如何上传图片
【发布时间】:2014-03-11 16:56:50
【问题描述】:

上传文件时出现以下错误。

参数字典包含一个 参数“category_id”的空条目 不可为空的类型'System.Int32' 对于方法 'System.Web.Mvc.ActionResult AddProduct(Int32, System.String, 单,System.String,System.String, 系统字符串,系统字符串, System.String, System.String)' 在 '电子商务.Controllers.AdminController'。 使参数可选其类型 应该是引用类型或 可空类型。参数名称: 参数

我正在使用一个对话框。

观点

<script type="text/javascript">
        $(function() {
        $("#dialog").dialog({
            bgiframe: true,
            height: 140,
            modal: true,
            autoOpen: false, 
            resizable: false
            })
    });

</script>

<div id="dialog" title="Upload files">
    <% using (Html.BeginForm("Upload", "File", FormMethod.Post, new { enctype = "multipart/form-data" }))
        {%>
            <p><input type="file" id="fileUpload" name="fileUpload" size="23"/> </p>
            <p><input type="submit" value="Upload file" /></p>
        <% } %>
</div>

<p>
    <label for="image_name">image_name:</label>
    <a href="#" onclick="jQuery('#dialog').dialog('open'); return false">Upload File</a>

    <%= Html.ValidationMessage("image_name", "*") %>
</p>

控制器动作

public ActionResult AddProduct(int category_id, string product_name, float product_price, string product_desc, string weight, string image_name, string img_content, string available_qty, string isFeature)
{

    foreach (string inputTagName in Request.Files)
    {
        HttpPostedFileBase file = Request.Files[inputTagName];
        if (file.ContentLength > 0)
        {
            string filePath = Path.Combine(HttpContext.Server.MapPath("../Uploads"), Path.GetFileName(file.FileName));
            string filecontent = Path.Combine(HttpContext.Server.MapPath("../Uploads"), Path.GetFileName(file.ContentType));

            image_name = Path.GetFileName(file.FileName);
            img_content = Path.GetFileName(file.ContentType);

            file.SaveAs(filePath);
        }
    }

    AdminImplementation _adminImplementation = new AdminImplementation();

    Boolean isfeature = Convert .ToBoolean(isFeature);

    if (isfeature)
    {
        isFeature = "Featured";
    }
    else
    {
        isFeature = "NotFeatured";
    }


    int i = _adminImplementation.addproduct(category_id, product_name, product_price, product_desc, weight,image_name ,img_content ,available_qty ,isFeature );

    ViewData["succm"] = "Product added successfully";
    return View();
}

请提出一些有用的答案。

谢谢

丽兹

【问题讨论】:

  • 我们还需要方法签名。
  • 现在我已经解决了您的问题,请提供最初呈现页面的 ViewResult。我需要知道缺失值在哪里。此外,如果您不知道为什么会出现此错误,我建议您访问 www.asp.net/mvc/,因为您似乎不了解 ASP.NET 中 MVC 架构的一些基本元素。

标签: asp.net-mvc upload


【解决方案1】:

在我看来,您没有提供特定 ActionResult 所需的所有参数。 category_id 未提供给 AddProduct。您需要向我们展示您的代码,以便我们找出真正的问题所在。

你怎么称呼那个 ActionResult?

【讨论】:

    【解决方案2】:
    **UPLOADING IMAGE AND SAVING PATH IN THE DATABASE
    ________________________________________________________________________________________
    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>
    </head>
    <body>
    <div>
                <h3> Choose File to Upload in Server </h3>          
               <form action="Recent" method="post" enctype="multipart/form-data">
    
                <input type="file" name="file" />
                <input type="submit" value="upload" />
                </form>          
            </div>
    
    
    </body>
    </html>
    ____________________________________________________________________________________________
    
    import java.sql.*;
    import java.io.*;
    
    import javax.servlet.ServletException;
    import javax.servlet.annotation.MultipartConfig;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.Part;
    import javax.servlet.annotation.MultipartConfig;
    import javax.servlet.annotation.WebServlet;
    import java.util.Hashtable;
    import java.util.List;
    
    import org.apache.commons.fileupload.FileItem;
    import org.apache.commons.fileupload.ParameterParser;
    import org.apache.commons.fileupload.disk.DiskFileItemFactory;
    import org.apache.commons.fileupload.servlet.ServletFileUpload;
    
    
    /**
     * Servlet implementation class Recent
     */
    @WebServlet("/Recent")
    @MultipartConfig
    public class Recent extends HttpServlet {
        private static final long serialVersionUID = 1L;
    
        /**
         * @see HttpServlet#HttpServlet()
         */
        public Recent() {
            super();
            // TODO Auto-generated constructor stub
        }
    
        /**
         * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
         */
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
            // TODO Auto-generated method stub
             Sample  s1=new Sample();
             final String UPLOAD_DIRECTORY = "/home/pradeep/Documents/pradeep/WebContent/Images";
             if(ServletFileUpload.isMultipartContent(request)){
                    try {
             List<FileItem> multiparts = new 
                                ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
    
                        for(FileItem item : multiparts){
                            if(!item.isFormField())
                            {
                                String name = new File(item.getName()).getName();
                                item.write( new File(UPLOAD_DIRECTORY + File.separator + name));
                                String Path= "/home/pradeep/Documents/pradeep/WebContent/Images/" +name;
    
    
                              s1.connecting(Path);
    
    
                            }
                        }
    
                            request.setAttribute("message", "File Uploaded Successfully");
                    } catch (Exception ex) {
                       request.setAttribute("message", "File Upload Failed due to " + ex);
                    }          
    
                }else{
                    request.setAttribute("message",
                                         "Sorry this Servlet only handles file upload request");
                }
    
    
    
                    request.getRequestDispatcher("/Result.jsp").forward(request, response);
    
    
    
    
        }
    
    }
    __________________________________________________________________________________________
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    
    import dbconnections.Connections;
    
    
    
    public class Sample {
        Connections con=new Connections();
    
        public void connecting(String Path)
        {
            Connection conn=con.Connect();
    
            PreparedStatement pst;
            String query="INSERT INTO Student1 (Path) values (?)";
           try {
    
                pst=conn.prepareStatement(query);
                pst.setString(1,Path);
                pst.executeUpdate();
    
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    
            // TODO Auto-generated method stub
        }
    
    
    }
    

    【讨论】:

      猜你喜欢
      • 2012-07-16
      • 2010-11-22
      • 2021-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多