如何将图像上传到服务器并保存其路径

时间:2014-10-27 13:16:11

标签: asp.net-mvc asp.net-mvc-5

我希望能够将图像上传到服务器,但不是将图像保存为数据库中的字节而是要保存路径,以便在视图页面中我通过它的路径调用图像。上传它应该上传到某个文件夹,如果找不到文件夹创建one.all这应该是使用MVC5任何帮助真的很感激

1 个答案:

答案 0 :(得分:1)

不确定您要使用哪种语言,但这是将照片保存到数据库后所需的实现方法。 (基本上就是你的说法)

  1. 照片已压缩
  2. 照片发送到服务器
  3. 服务器的api处理文件存储到文件夹
  4. 保存文件夹路径+'文件名'进入数据库
  5. 这是一个PHP方法upload(),它是处理步骤3和4的服务器API的一部分

    Ray Wenderlich

    上找到
    //upload API
    function upload($id, $photoData, $title) {
    
        // index.php passes as first parameter to this function $_SESSION['IdUser']
        // $_SESSION['IdUser'] should contain the user id, if the user has already been authorized
        // remember? you store the user id there in the login function
        if (!$id) errorJson('Authorization required');
    
        // check if there was no error during the file upload
        if ($photoData['error']==0) {
    
            // insert the details about the photo to the "photos" table
            $result = query("INSERT INTO photos(IdUser,title) VALUES('%d','%s')", $id, $title);
            if (!$result['error']) {
    
                // fetch the active connection to the database (it's initialized automatically in lib.php)
                global $link;
    
                // get the last automatically generated ID in the photos table
                $IdPhoto = mysqli_insert_id($link);
    
                // move the temporarily stored file to a convenient location
                // your photo is automatically saved by PHP in a temp folder
                // you need to move it over yourself to your own "upload" folder
                if (move_uploaded_file($photoData['tmp_name'], "upload/".$IdPhoto.".jpg")) {
    
                    // file moved, all good, generate thumbnail
                    thumb("upload/".$IdPhoto.".jpg", 180);
    
                    //just print out confirmation to the iPhone app
                    print json_encode(array('successful'=>1));
                } else {
                    //print out an error message to the iPhone app
                    errorJson('Upload on server problem');
                };
    
            } else {
                errorJson('Upload database problem.'.$result['error']);
            }
        } else {
            errorJson('Upload malfunction');
        }
    }