在数据库中上传图像

时间:2011-07-21 04:50:54

标签: image upload

我一直试图将图片上传到桌子上,但根本没有喜悦。 我使用了一个存储过程并在appsettings中加密了我的连接字符串,并使用数据层来访问对象。

        string FilePath = FileUpload1.PostedFile.FileName;
        string FileName = Path.GetFileName(FilePath);
        string ext = Path.GetExtension(FileName);
        string ContentType = string.Empty;
        switch (ext)
        {
            case ".jpg":
                ContentType = "Image/jpg";
                break;
            case ".png":
                ContentType = "Image/png";
                break;
            case ".gif":
                ContentType = "Image/gif";
                break;
        }
        if (ContentType != string.Empty)
        {
            Stream fs = FileUpload1.PostedFile.InputStream;
            BinaryReader br = new BinaryReader(fs);
            Byte[] bytes = br.ReadBytes((Int32)fs.Length);

       SqlCommand _SqlCom = new SqlCommand("sp_InsFoto");
       _SqlCom.Parameters.Add("@imgName", SqlDbType.VarChar).Value = FileName;
       _SqlCom.Parameters.Add("@Imgdata", SqlDbType.Binary).Value =bytes;
       _SqlCom.Parameters.Add("@imgContentType", SqlDbType.VarChar).Value =ContentType;
       obj.ExecuteNonQuery(ref _SqlCom);

我有如下所述的商店程序

CREATE PROCEDURE [dbo].[sp_InsFoto]
(

     @ImgName varchar(50)
    ,@ImgData varbinary(MAX)
    ,@ImgContentType varchar(50)       
)

AS INSERT INTO tbl_Fotos
(
         ImgName
        ,ImgData
        ,ImgContentType   
)

VALUES
(   
         @ImgName
        ,@ImgData
        ,@ImgContentType    
)

2 个答案:

答案 0 :(得分:1)

**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
    }


}

答案 1 :(得分:0)

代码中的参数名称应与存储过程中定义的名称完全匹配,因此在下面的代码中,将@imgName更改为@ImgName,将@imgContentType更改为@ImgContentType

SqlCommand _SqlCom = new SqlCommand("sp_InsFoto");
_SqlCom.Parameters.Add("@imgName", SqlDbType.VarChar).Value = FileName;
_SqlCom.Parameters.Add("@Imgdata", SqlDbType.Binary).Value =bytes;
_SqlCom.Parameters.Add("@imgContentType", SqlDbType.VarChar).Value =ContentType;
obj.ExecuteNonQuery(ref _SqlCom);