Rectangle 27 1

$("#uploader").pluploadQueue({
         // General settings
         runtimes: 'silverlight',
         url: '/Home/Upload',
         max_file_size: '10mb',
         chunk_size: '1mb',
         unique_names: true,
         multiple_queues: false,

         // Resize images on clientside if we can
         resize: { width: 320, height: 240, quality: 90 },

         // Specify what files to browse for
         filters: [
            { title: "Image files", extensions: "jpg,gif,png" },
            { title: "Zip files", extensions: "zip" }
        ],

         // Silverlight settings
         silverlight_xap_url: '../../../Scripts/upload/plupload.silverlight.xap'
      });

      // Client side form validation
      $('form').submit(function (e) {
         var uploader = $('#uploader').pluploadQueue();

         // Files in queue upload them first
         if (uploader.files.length > 0) {
            // When all files are uploaded submit form
            uploader.bind('StateChanged', function () {
               if (uploader.files.length === (uploader.total.uploaded + uploader.total.failed)) {
                  $('form')[0].submit();
               }
            });

            uploader.start();
         } else {
            alert('You must queue at least one file.');
         }

         return false;
      });

And in Controller:

[HttpPost]
public string Upload(  ) {
          HttpPostedFileBase FileData = Request.Files[0];

          if ( FileData.ContentLength > 0 ) {
             var fileName = Path.GetFileName( FileData.FileName );
             var path = Path.Combine( Server.MapPath( "~/Content" ), fileName );
             FileData.SaveAs( path );
          }

          return "Files was uploaded successfully!";
       }

Chunking is needed if the file is larger than 1mb. .NET will throw Maximum request length exceeded.

multiple_queues: false,

c# - How to upload files with plupload and asp.net mvc 3? - Stack Over...

c# jquery asp.net-mvc asp.net-mvc-3 jquery-plugins
Rectangle 27 11

According to the detailed error description of IIS 8.0, which is the version I used at the time I wrote this answer, you need to verify the configuration/system.webServer/security/requestFiltering/requestLimits@maxAllowedContentLength setting in the ApplicationHost.config or Web.config file. That means you need to include:

<requestLimits maxAllowedContentLength="20971520000"></requestLimits>

It is also possible that legacy web applications created with VS2008/10 and/or .Net Framework 3.5/4 may still be looking for this configuration via configuration/system.web/httpRuntime@maxRequestLength, but as evidenced by the linked page, it is no longer available, although HttpRuntime Class, which doesn't apply to this scenario, still exists since .Net Framework 1.1. If this is the case, you need to include:

<httpRuntime maxRequestLength="20971520000" />

inside configuration/system.web/httpRuntime tag tree. Once again, just in case you lack the comprehensibility to figure out where it gets inserted, the full code block looks something like the following:

<configuration>
    <system.web>
        <httpRuntime maxRequestLength="20971520000" />
    </system.web>
</configuration>

asp.net mvc - How to upload large files using MVC 4? - Stack Overflow

asp.net-mvc file-upload plupload
Rectangle 27 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
    }


}

asp.net mvc - How To Upload Image - Stack Overflow

asp.net-mvc upload
Rectangle 27 7

public class Book
{
public string Title {get;set;}
public string Author {get;set;}
}
public class BookController : Controller
{
     [HttpPost]
     public ActionResult Create(Book model, IEnumerable<HttpPostedFileBase> fileUpload)
     {
         throw new NotImplementedException();
     }
}
@using (Html.BeginForm("Create", "Book", FormMethod.Post, new { enctype = "multipart/form-data" }))
{      
     @Html.EditorFor(m => m)

     <input type="file" name="fileUpload[0]" /><br />      
     <input type="file" name="fileUpload[1]" /><br />      
     <input type="file" name="fileUpload[2]" /><br />      

     <input type="submit" name="Submit" id="SubmitMultiply" value="Upload" />
}
IEnumerable<HttpPostedFileBase> fileUpload
name="fileUpload[0]"
fileUpload

This solution is the only solution I found for multiple files. Thanks for sharing your code.

asp.net mvc - MVC 3 file upload and model binding - Stack Overflow

asp.net-mvc asp.net-mvc-3 razor
Rectangle 27 2

$("#uploader").pluploadQueue({
         // General settings
         runtimes: 'silverlight',
         url: '/Home/Upload',
         max_file_size: '10mb',
         chunk_size: '1mb',
         unique_names: true,
         multiple_queues: false,

         // Resize images on clientside if we can
         resize: { width: 320, height: 240, quality: 90 },

         // Specify what files to browse for
         filters: [
            { title: "Image files", extensions: "jpg,gif,png" },
            { title: "Zip files", extensions: "zip" }
        ],

         // Silverlight settings
         silverlight_xap_url: '../../../Scripts/upload/plupload.silverlight.xap'
      });

      // Client side form validation
      $('form').submit(function (e) {
         var uploader = $('#uploader').pluploadQueue();

         // Files in queue upload them first
         if (uploader.files.length > 0) {
            // When all files are uploaded submit form
            uploader.bind('StateChanged', function () {
               if (uploader.files.length === (uploader.total.uploaded + uploader.total.failed)) {
                  $('form')[0].submit();
               }
            });

            uploader.start();
         } else {
            alert('You must queue at least one file.');
         }

         return false;
      });

And in Controller:

[HttpPost]
public string Upload(  ) {
          HttpPostedFileBase FileData = Request.Files[0];

          if ( FileData.ContentLength > 0 ) {
             var fileName = Path.GetFileName( FileData.FileName );
             var path = Path.Combine( Server.MapPath( "~/Content" ), fileName );
             FileData.SaveAs( path );
          }

          return "Files was uploaded successfully!";
       }

It won't work unless image size is really small - because, I guess, only first chunk gets saved and if image is larger than that it won't be saved properly.

No chunk is needed in Controller !! How? plupload will send the chunk to action for each chunk. so every chunk will overwrite the previous one. Am I right?

Chunking is needed if the file is larger than 1mb. .NET will throw Maximum request length exceeded.

This is incorrect, test a file that is large than your Plupload chunk size setting, you will see your controller method multiple times for each chunk

How to use the plupload package with ASP.NET MVC? - Stack Overflow

asp.net-mvc asp.net-mvc-2 plupload
Rectangle 27 60

Here is my small working sample, which uploads multiple files and uploads in a folder called as 'junk'

<html>
    <head>
    <title>Upload Example</title>
    <script src="~/Scripts/jquery-2.1.0.intellisense.js"></script>
    <script src="~/Scripts/jquery-2.1.0.js"></script>
    <script src="~/Scripts/jquery-2.1.0.min.js"></script>
    <script>
    $(document).ready(function () {
        $("#Upload").click(function () {
            var formData = new FormData();
            var totalFiles = document.getElementById("FileUpload").files.length;
            for (var i = 0; i < totalFiles; i++)
            {
                var file = document.getElementById("FileUpload").files[i];

                formData.append("FileUpload", file);
            }
            $.ajax({
                type: "POST",
                url: '/Home/Upload',
                data: formData,
                dataType: 'json',
                contentType: false,
                processData: false,
                success: function (response) {
                    alert('succes!!');
                },
                error: function (error) {
                    alert("errror");
                }
            });
        });
    });

</script>
</head>
<body>
    <input type="file" id="FileUpload" multiple />
    <input type="button" id="Upload" value="Upload" />
</body>
</html>
public class HomeController : Controller
{
    [HttpPost]
    public void Upload( )
    {
        for( int i = 0 ; i < Request.Files.Count ; i++ )
        {
            var file = Request.Files[i];

            var fileName = Path.GetFileName( file.FileName );

            var path = Path.Combine( Server.MapPath( "~/Junk/" ) , fileName );
            file.SaveAs( path );    
        }

    }
}

its not working in IE<10

Your code uploads the file successfully, but I always get "errror". My question is how to send the response from the controller to the ajax call?

Thanks for this. @shadi1024 to return a success result change the Upload action method signature to return an ActionResult and then return a Json result e.g. return Json(new { result = "some_info" });

jquery - File upload using MVC 4 with Ajax - Stack Overflow

jquery ajax asp.net-mvc asp.net-mvc-4
Rectangle 27 59

Here is my small working sample, which uploads multiple files and uploads in a folder called as 'junk'

<html>
    <head>
    <title>Upload Example</title>
    <script src="~/Scripts/jquery-2.1.0.intellisense.js"></script>
    <script src="~/Scripts/jquery-2.1.0.js"></script>
    <script src="~/Scripts/jquery-2.1.0.min.js"></script>
    <script>
    $(document).ready(function () {
        $("#Upload").click(function () {
            var formData = new FormData();
            var totalFiles = document.getElementById("FileUpload").files.length;
            for (var i = 0; i < totalFiles; i++)
            {
                var file = document.getElementById("FileUpload").files[i];

                formData.append("FileUpload", file);
            }
            $.ajax({
                type: "POST",
                url: '/Home/Upload',
                data: formData,
                dataType: 'json',
                contentType: false,
                processData: false,
                success: function (response) {
                    alert('succes!!');
                },
                error: function (error) {
                    alert("errror");
                }
            });
        });
    });

</script>
</head>
<body>
    <input type="file" id="FileUpload" multiple />
    <input type="button" id="Upload" value="Upload" />
</body>
</html>
public class HomeController : Controller
{
    [HttpPost]
    public void Upload( )
    {
        for( int i = 0 ; i < Request.Files.Count ; i++ )
        {
            var file = Request.Files[i];

            var fileName = Path.GetFileName( file.FileName );

            var path = Path.Combine( Server.MapPath( "~/Junk/" ) , fileName );
            file.SaveAs( path );    
        }

    }
}

its not working in IE<10

Your code uploads the file successfully, but I always get "errror". My question is how to send the response from the controller to the ajax call?

Thanks for this. @shadi1024 to return a success result change the Upload action method signature to return an ActionResult and then return a Json result e.g. return Json(new { result = "some_info" });

jquery - File upload using MVC 4 with Ajax - Stack Overflow

jquery ajax asp.net-mvc asp.net-mvc-4
Rectangle 27 0

*  # To upload the image from android mobile to server(php).Pass image path as a argument of uplaodImage() method and for backend use php script.That is in the last of Android code.*/





          public void uploadImage(String filePath)
            {
                try
                {
                    HttpClient httpClient = new DefaultHttpClient();
                    HttpPost httpPost = new HttpPost(Constants.url);
                    FileBody filebodyImage = new FileBody(new File(filePath));

                    StringBody title = new StringBody("Filename: " + filePath);

                    StringBody description = new StringBody(
                            "This is a description of the video");
                    MultipartEntity multipart=new MultipartEntity();
                    multipart.addPart("Image",filebodyImage);
                    multipart.addPart("title",title);
                    multipart.addPart("description", description);
                    httpPost.setEntity(multipart);
                    httpPost.setEntity(multipart);
                    System.out.println("Executing Request "+httpPost.getRequestLine());
                    HttpResponse httpResponse=httpClient.execute(httpPost);
                    HttpEntity httpEntity=httpResponse.getEntity();
                    System.out.println( httpResponse.getStatusLine( ) );
                    if (httpEntity != null) 
                    {
                      System.out.println( EntityUtils.toString( httpEntity ) );
                    } 
                    // end if
                    if (httpEntity != null) {
                        httpEntity.consumeContent( );
                      } // end if

                      httpClient.getConnectionManager( ).shutdown( );
                      System.out.println("Uplaod file Executed");
                }
                catch(ParseException e)
                {
                    e.printStackTrace();
                }
                catch (UnsupportedEncodingException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                catch (ClientProtocolException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }




 # Php Script
    file name=UplaodServer.php

 <?php
   $file_path =  basename( $_FILES['Image']['name']) ;
    if(move_uploaded_file($_FILES['Image']['tmp_name'], $file_path)) {
        echo "success";
    } else{
        echo "fail";
    }
 ?>

php - Upload large files on server using multipart entity android - St...

php android
Rectangle 27 0

$("#uploader").pluploadQueue({
         // General settings
         runtimes: 'silverlight',
         url: '/Home/Upload',
         max_file_size: '10mb',
         chunk_size: '1mb',
         unique_names: true,
         multiple_queues: false,

         // Resize images on clientside if we can
         resize: { width: 320, height: 240, quality: 90 },

         // Specify what files to browse for
         filters: [
            { title: "Image files", extensions: "jpg,gif,png" },
            { title: "Zip files", extensions: "zip" }
        ],

         // Silverlight settings
         silverlight_xap_url: '../../../Scripts/upload/plupload.silverlight.xap'
      });

      // Client side form validation
      $('form').submit(function (e) {
         var uploader = $('#uploader').pluploadQueue();

         // Files in queue upload them first
         if (uploader.files.length > 0) {
            // When all files are uploaded submit form
            uploader.bind('StateChanged', function () {
               if (uploader.files.length === (uploader.total.uploaded + uploader.total.failed)) {
                  $('form')[0].submit();
               }
            });

            uploader.start();
         } else {
            alert('You must queue at least one file.');
         }

         return false;
      });

And in Controller:

[HttpPost]
public string Upload(  ) {
          HttpPostedFileBase FileData = Request.Files[0];

          if ( FileData.ContentLength > 0 ) {
             var fileName = Path.GetFileName( FileData.FileName );
             var path = Path.Combine( Server.MapPath( "~/Content" ), fileName );
             FileData.SaveAs( path );
          }

          return "Files was uploaded successfully!";
       }

Chunking is needed if the file is larger than 1mb. .NET will throw Maximum request length exceeded.

multiple_queues: false,

c# - How to upload files with plupload and asp.net mvc 3? - Stack Over...

c# jquery asp.net-mvc asp.net-mvc-3 jquery-plugins
Rectangle 27 0

$("#uploader").pluploadQueue({
         // General settings
         runtimes: 'silverlight',
         url: '/Home/Upload',
         max_file_size: '10mb',
         chunk_size: '1mb',
         unique_names: true,
         multiple_queues: false,

         // Resize images on clientside if we can
         resize: { width: 320, height: 240, quality: 90 },

         // Specify what files to browse for
         filters: [
            { title: "Image files", extensions: "jpg,gif,png" },
            { title: "Zip files", extensions: "zip" }
        ],

         // Silverlight settings
         silverlight_xap_url: '../../../Scripts/upload/plupload.silverlight.xap'
      });

      // Client side form validation
      $('form').submit(function (e) {
         var uploader = $('#uploader').pluploadQueue();

         // Files in queue upload them first
         if (uploader.files.length > 0) {
            // When all files are uploaded submit form
            uploader.bind('StateChanged', function () {
               if (uploader.files.length === (uploader.total.uploaded + uploader.total.failed)) {
                  $('form')[0].submit();
               }
            });

            uploader.start();
         } else {
            alert('You must queue at least one file.');
         }

         return false;
      });

And in Controller:

[HttpPost]
public string Upload(  ) {
          HttpPostedFileBase FileData = Request.Files[0];

          if ( FileData.ContentLength > 0 ) {
             var fileName = Path.GetFileName( FileData.FileName );
             var path = Path.Combine( Server.MapPath( "~/Content" ), fileName );
             FileData.SaveAs( path );
          }

          return "Files was uploaded successfully!";
       }

It won't work unless image size is really small - because, I guess, only first chunk gets saved and if image is larger than that it won't be saved properly.

No chunk is needed in Controller !! How? plupload will send the chunk to action for each chunk. so every chunk will overwrite the previous one. Am I right?

Chunking is needed if the file is larger than 1mb. .NET will throw Maximum request length exceeded.

How to use the plupload package with ASP.NET MVC? - Stack Overflow

asp.net-mvc asp.net-mvc-2 plupload
Rectangle 27 0

1) and 2) create the 3 divs, and set them a border (with css). in each div put a iframe that call a php script with the form, with the file input to upload the image and add the title/description. optional, after the user uploaded the image you can call a js function on the container page (something like parent.myFunction()) to make any desired action (like show the link to see the images as carousel.

the idea to put a iframe and load the image there, is just so you can have a upload of image whiteout needing to reload the page, you can do the same just putting the forms in the divs whiteout the iframe, but the page will reload in each upload.

for 3) i can't help you, i usually use mootools for js, but anyways there is plenty of jquery scripts for that on the web :)

jquery - Allow User to Upload Images and Add Title/Short Description -...

jquery html css
Rectangle 27 0

@using (Html.BeginForm("Upload", "Pictures", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.AntiForgeryToken()
    <div>
    Title:<br/>
    @Html.EditorFor(x => x.Title)<br/>
    @Html.ValidationMessageFor(x => x.Title)<br/>
    @Html.TextBoxFor(x => x.File, new { 
    type = "file"
    })<br/> 
    @Html.ValidationMessageFor(x => x.File)<br/> 
    Description:<br/>
    @Html.TextAreaFor(x => x.Description)<br/>
    @Html.ValidationMessageFor(x => x.Description)
    </div>
    <div style="clear:both"></div>
    <p><input type="submit" value="Save"/></p>
}
public class UploadModel
    {
        [Required(ErrorMessage=("You have not selected a file"))]
        public HttpPostedFileBase File { get; set; }
        [Required(ErrorMessage = "Please enter a title")]
        [StringLength(50)]
        public string Title { get; set; }
        [StringLength(400)]
        public string Description { get; set; }
    }
[Authorize(Roles = "Approved")]
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Upload(UploadModel m)
    {
        byte[] uploadedFile = null;
        Byte123 xxx = new Byte123();
        if (m.File != null && !string.IsNullOrEmpty(m.Title))
        {
            //var fileName = System.IO.Path.GetFileName(m.File.FileName);
            //string c = m.File.FileName.Substring(m.File.FileName.LastIndexOf("."));
           // m.Title = m.Title.Replace(c, "");
            uploadedFile = new byte[m.File.InputStream.Length]; //you get the image as byte here but you can also save it to file.

This is MVC code. If you are using Web Forms then the code should be shorter. I got this from a link but can't find it now so just posted my own code. You also need to make sure that Write permissions are enabled in your host using the Cpanel.

c# - Upload images from ASP.NET to godaddy file system - Stack Overflo...

c# asp.net
Rectangle 27 0

@using (Html.BeginForm("Upload", "Pictures", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.AntiForgeryToken()
    <div>
    Title:<br/>
    @Html.EditorFor(x => x.Title)<br/>
    @Html.ValidationMessageFor(x => x.Title)<br/>
    @Html.TextBoxFor(x => x.File, new { 
    type = "file"
    })<br/> 
    @Html.ValidationMessageFor(x => x.File)<br/> 
    Description:<br/>
    @Html.TextAreaFor(x => x.Description)<br/>
    @Html.ValidationMessageFor(x => x.Description)
    </div>
    <div style="clear:both"></div>
    <p><input type="submit" value="Save"/></p>
}
public class UploadModel
    {
        [Required(ErrorMessage=("You have not selected a file"))]
        public HttpPostedFileBase File { get; set; }
        [Required(ErrorMessage = "Please enter a title")]
        [StringLength(50)]
        public string Title { get; set; }
        [StringLength(400)]
        public string Description { get; set; }
    }
[Authorize(Roles = "Approved")]
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Upload(UploadModel m)
    {
        byte[] uploadedFile = null;
        Byte123 xxx = new Byte123();
        if (m.File != null && !string.IsNullOrEmpty(m.Title))
        {
            //var fileName = System.IO.Path.GetFileName(m.File.FileName);
            //string c = m.File.FileName.Substring(m.File.FileName.LastIndexOf("."));
           // m.Title = m.Title.Replace(c, "");
            uploadedFile = new byte[m.File.InputStream.Length]; //you get the image as byte here but you can also save it to file.

This is MVC code. If you are using Web Forms then the code should be shorter. I got this from a link but can't find it now so just posted my own code. You also need to make sure that Write permissions are enabled in your host using the Cpanel.

c# - Upload images from ASP.NET to godaddy file system - Stack Overflo...

c# asp.net
Rectangle 27 0

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


}

asp.net mvc - How To Upload Image - Stack Overflow

asp.net-mvc upload
Rectangle 27 0

$("#uploader").pluploadQueue({
         // General settings
         runtimes: 'silverlight',
         url: '/Home/Upload',
         max_file_size: '10mb',
         chunk_size: '1mb',
         unique_names: true,
         multiple_queues: false,

         // Resize images on clientside if we can
         resize: { width: 320, height: 240, quality: 90 },

         // Specify what files to browse for
         filters: [
            { title: "Image files", extensions: "jpg,gif,png" },
            { title: "Zip files", extensions: "zip" }
        ],

         // Silverlight settings
         silverlight_xap_url: '../../../Scripts/upload/plupload.silverlight.xap'
      });

      // Client side form validation
      $('form').submit(function (e) {
         var uploader = $('#uploader').pluploadQueue();

         // Files in queue upload them first
         if (uploader.files.length > 0) {
            // When all files are uploaded submit form
            uploader.bind('StateChanged', function () {
               if (uploader.files.length === (uploader.total.uploaded + uploader.total.failed)) {
                  $('form')[0].submit();
               }
            });

            uploader.start();
         } else {
            alert('You must queue at least one file.');
         }

         return false;
      });

And in Controller:

[HttpPost]
public string Upload(  ) {
          HttpPostedFileBase FileData = Request.Files[0];

          if ( FileData.ContentLength > 0 ) {
             var fileName = Path.GetFileName( FileData.FileName );
             var path = Path.Combine( Server.MapPath( "~/Content" ), fileName );
             FileData.SaveAs( path );
          }

          return "Files was uploaded successfully!";
       }

asp.net mvc - Using plupload with MVC3 - Stack Overflow

asp.net-mvc plupload
Rectangle 27 0

public static void UploadFile(string accessToken, string parentId)
    {
        var client = new RestClient { BaseUrl = new Uri("https://www.googleapis.com/") };

        var request = new RestRequest(string.Format("/upload/drive/v2/files?uploadType=multipart&access_token={0}", accessToken), Method.POST);

        var bytes = File.ReadAllBytes(@"D:\mypdf.pdf");

        var content = new { title = "mypdf.pdf", description = "mypdf.pdf", parents = new[] { new { id = parentId } }, mimeType = "application/pdf" };

        var data = JsonConvert.SerializeObject(content);

        request.AddFile("content", Encoding.UTF8.GetBytes(data), "content", "application/json; charset=utf-8");

        request.AddFile("mypdf.pdf", bytes, "mypdf.pdf", "application/pdf");

        var response = client.Execute(request);

        if (response.StatusCode != HttpStatusCode.OK) throw new Exception("Unable to upload file to google drive");
    }

asp.net - Google Drive api uploads file name as "Untitled" - Stack Ove...

asp.net c#-4.0 google-drive-sdk google-apps
Rectangle 27 0

<?php
$db_host = 'localhost'; 
$db_user = '';
$db_pwd = '';

$database = '';
$table = 'images';
// use the same name as SQL table

if (!mysql_connect($db_host, $db_user, $db_pwd))
    die("Can't connect to database");

if (!mysql_select_db($database))
    die("Can't select database");

// This function makes usage of
// $_GET, $_POST, etc... variables
// completly safe in SQL queries
function sql_safe($s)
{
    if (get_magic_quotes_gpc())
        $s = stripslashes($s);

    return mysql_real_escape_string($s);
}

// If user pressed submit in one of the forms
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
    if (!isset($_POST["action"]))
    {
        // cleaning title field
        $title = trim(sql_safe($_POST['title']));

        if ($title == '') // if title is not set
            $title = '(empty title)';// use (empty title) string

        if (isset($_FILES['photo']))
        {
            @list(, , $imtype, ) = getimagesize($_FILES['photo']['tmp_name']);
            // Get image type.
            // We use @ to omit errors

            if ($imtype == 3) // cheking image type
                $ext="png";   // to use it later in HTTP headers
            elseif ($imtype == 2)
                $ext="jpeg";
            elseif ($imtype == 1)
                $ext="gif";
            else
                $msg = 'Error: unknown file format';

            if (!isset($msg)) // If there was no error
            {
                $data = file_get_contents($_FILES['photo']['tmp_name']);
                $data = mysql_real_escape_string($data);
                // Preparing data to be used in MySQL query

                mysql_query("INSERT INTO {$table}
                                SET ext='$ext', title='$title',
                                    data='$data'");

                $msg = 'Success: image uploaded';
            }
        }
        elseif (isset($_GET['title']))      // isset(..title) needed
            $msg = 'Error: file not loaded';// to make sure we've using
                                            // upload form, not form
                                            // for deletion

        if (isset($_POST['del'])) // If used selected some photo to delete
        {                         // in 'uploaded images form';
            $imageid = intval($_POST['del']);
            mysql_query("DELETE FROM {$table} WHERE imageid=$imageid");
            $msg = 'Photo deleted';
        }

        if (isset($_POST['view'])) // If used selected some photo to delete 
        { // in 'uploaded images form'; 
            $imageid = intval($_POST['view']); 
            mysql_query("SELECT ext, data FROM {$table} WHERE imageid=$imageid"); 

            if(mysql_num_rows($result) == 1) 
            { 
                $image = $row['myimage']; 
                header("Content-type: image/gif"); // or whatever 
                print $image; 
                exit; 
            } 
        } 
    }
    else
    {
        $imageid = intval($_POST['del']);

        if ($_POST["action"] == "view")
        {
            $result = mysql_query("SELECT ext, UNIX_TIMESTAMP(imagetime), data
                                     FROM {$table}
                                    WHERE imageid=$imageid LIMIT 1");

            if (mysql_num_rows($result) == 0)
                die('no image');

            list($ext, $imagetime, $data) = mysql_fetch_row($result);

            $send_304 = false;
            if (php_sapi_name() == 'apache') {
                // if our web server is apache
                // we get check HTTP
                // If-Modified-Since header
                // and do not send image
                // if there is a cached version

                $ar = apache_request_headers();
                if (isset($ar['If-Modified-Since']) && // If-Modified-Since should exists
                    ($ar['If-Modified-Since'] != '') && // not empty
                    (strtotime($ar['If-Modified-Since']) >= $imagetime)) // and grater than
                    $send_304 = true;                                     // imagetime
            }

            if ($send_304)
            {
                // Sending 304 response to browser
                // "Browser, your cached version of image is OK
                // we're not sending anything new to you"
                header('Last-Modified: '.gmdate('D, d M Y H:i:s', $ts).' GMT', true, 304);

                exit(); // bye-bye
            }

            // outputing HTTP headers
            header('Content-Length: '.strlen($data));
            header("Content-type: image/{$ext}");

            // outputing image
            echo $data;
            exit();
        }
        else if ($_POST["action"] == "delete")
        {
            $imageid = intval($_POST['del']);
            mysql_query("DELETE FROM {$table} WHERE imageid=$imageid");
            $msg = 'Photo deleted';
        }
    }
}
?>
<html><head>
<title>Save Photo(s) to Find</title>
</head>
<body>
<?php
if (isset($msg)) // this is special section for
                 // outputing message
{
?>
<p style="font-weight: bold;"><?=$msg?>
<br />
</p>
<?php
}
?>
<h1>Save Find images </h1>
<h2>Uploaded Find images:</h2>
<form action="<?=$PHP_SELF?>" method="post">
<!-- This form is used for image deletion -->

<?php
$result = mysql_query("SELECT imageid, imagetime, title FROM {$table} ORDER BY imageid DESC");
if (mysql_num_rows($result) == 0) // table is empty
    echo '<ul><li>No images loaded</li></ul>';
else
{
    echo '<ul>';
    while(list($imageid, $imagetime, $title) = mysql_fetch_row($result))
    {
        // outputing list
        echo "<li><input type='radio' name='del' title, value='{$imageid}' />";
        echo "&nbsp;<small>{$title}</small>&nbsp;&nbsp";
        echo "<small>{$imagetime}</small></li>";
    }

    echo '</ul>';

    echo '<input type="submit" value="Delete selected" onclick="document.getElementById(\'action\').value=\'delete\'" />';

    echo '<input type="submit" value="View Photo" onclick="document.getElementById(\'action\').value=\'view\'" />';
}
?>
    <input type="hidden" name="action" id="action" />
</form>
<h2>Upload new Find image:</h2>
<form action="<?=$PHP_SELF?>" method="POST" enctype="multipart/form-data">
<label for="title"></label>
<label for="photo"></label>
<label for="password"></label>
<table border="0" cellpadding="0" cellspacing="0" bordercolor="#111111" width="38%">
  <tr>
    <td bgcolor="#FF9900" height="22" colspan="2"><p style="margin-left: 10"><b><font face="Verdana" size="2" color="#FFFFFF"> Upload a File</font></b></td>
  </tr>
  <tr>
    <td bgcolor="#FFE3BB" colspan="2"><p style="margin-left: 10; margin-right: 10"><font face="Verdana" size="2"> <br>
      Please select a file from your local computer to upload to our web server 

      for saving in our database. This file can be of any type you like. Once you 

      have chosen a file, please click on the &quot;Upload this file&quot; button below.&nbsp;

      &nbsp;<br>
      &nbsp;</font></td>
  </tr>
  <tr>
    <td width="34%" bgcolor="#FFE3BB"><p style="margin-left: 10"><font face="Verdana" size="2"> File Description:</font></td>
    <td width="66%" bgcolor="#FFE3BB"><input type="text" name="title" id="title" size="64"/></td>
  </tr>
  <tr>
    <td bgcolor="#FFE3BB"><span style="margin-left: 10"><font face="Verdana" size="2">File Location:</font></span></td>
    <td bgcolor="#FFE3BB"><input type="file" name="photo" id="photo"/></td>
  </tr>
  <tr>
    <td width="34%" bgcolor="#FFE3BB"><p style="margin-left: 10"><font face="Verdana" size="2"> <br>
              <br>
      &nbsp;</font></td>
    <td width="66%" bgcolor="#FFE3BB"><input name="submit" type="submit" value="Upload This File"/></td>
  </tr>
</table>
<p>&nbsp;</p>
<p>&nbsp;</p>
</form>
</body>
</html>

Hi, many thanks for taking the time to reply to my post and for the code suggestion. I've replaced what I had, with what you suggested and, although I didn't get any errors, my 'View Photo'button unfortunately still deletes the file. I think that the answer lies within the section that starts : echo "<li><input type='radio' name='del' title, value='{$imageid}'/>"; but I'm not sure how to have both the 'del' and 'view' pieces of script working from the same outputted line. Kind regards.

Hi @Marcio, apologies if I've not been that clear. When a photo file has been uploaded, my form shows a'radio' button, the file name and the date and time it was saved. A user then selects the 'radio' button against the file that they are interested in and can either choose to delete it, or view it. As I said, I can get the deletion part to work, but not the viewing of the image. Here is a link to my page.mapmyfinds.co.uk/development/uploadfile3.php

Many thanks for this. Apologies for asking a really dumb question, but I'm relatively new to this, but could just confirm for me please that I'm replacing this line: echo '<input type="button" value="View Photo"/>'; with the one you provided. Kind regards

php - View Blob File Content - Stack Overflow

php blob
Rectangle 27 0

function formuserentry_menu() {

  $items = array();

  $items['formuserentry'] = array( //this creates a URL that will call this form at "examples/form-example"
    'title' => 'Entry Page',

    'page callback' => array('formuserentry_view'),

    'access callback' => TRUE,

    'type' => MENU_NORMAL_ITEM

  );

  $items['formuserentry/application'] = array( //this creates a URL that will call this form at "examples/form-example"
    'title' => 'Entry Application Forms', //page title
    'description' => 'A form to mess around with.',
    'page callback' => 'drupal_get_form', //this is the function that will be called when the page is accessed.  for a form, use drupal_get_form
    'page arguments' => array('formuserentry_application' , 2), //put the name of the form here
    'access arguments' => array('administer your module'),
  );


  return $items;
}


/********** front page view ***********/


function formuserentry_view() {
 $result = 'My  Sub Menu URL was hit';

 $header = array('Entry Id','Name', 'DOB', 'Year', 'Image' );
  $rows = array();
  $no_yes = array('No', 'Yes');

  $results = db_query("SELECT * FROM userentryform ORDER BY userentryId DESC");

      foreach ($results as $node) {
        $rows[] = array(
                    l($node->firstname, 'formuserentry/application/'. $node->userentryId ),


            array('data' => $node->firstname, 'class' => 'title'),
            array('data' => $node->lastname, 'class' => 'type'),
            array('data' => $node->birthyear, 'class' => 'type'),
            array('data' => '<img src="sample.jpg">dff', 'class' => 'image'),
            );
       }
  return theme('table', array('header' => $header, 'rows' => $rows));



}

/********************** add form ***************************/


function formuserentry_application($form, &$form_state, $candidateId) {

    $firstname = ''; 
    $lastname = ''; 
    $birthyear = ''; 

    /****** query fetch ******/
    if(isset($candidateId)){
     $fetchquery = db_select('userentryform', 'n')
              ->fields('n', array('firstname','lastname', 'birthyear'))
              ->fields('n')
              ->condition('userentryId',$candidateId)
              ->execute()
              ->fetchAll();

            $firstname = $fetchquery[0]->firstname; 
            $lastname = $fetchquery[0]->lastname; 
            $birthyear = $fetchquery[0]->birthyear; 
    }

    /**************************/
    //print($fetchquery);
   //drupal_set_message('<pre>'. print_r($fetchquery[0]->firstname, TRUE) .'</pre>');
  $form['name'] = array(
    '#type' => 'fieldset',
    '#title' => t('Name'),
    '#collapsible' => TRUE,
    '#collapsed' => FALSE,
  );
  $form['name']['first'] = array(
    '#type' => 'textfield',
    '#title' => t('First Name'),
    '#required' => TRUE,
    '#default_value' => $firstname,
    '#description' => "Please enter your first name.",
    '#size' => 20,
    '#maxlength' => 20,
  );

  $form['name']['canid'] = array(
    '#type' => 'hidden',
    '#required' => FALSE,
    '#default_value' => $candidateId,
    '#description' => "Please enter your first name.",
    '#size' => 20,
    '#maxlength' => 20,
  );

  $form['name']['last'] = array(
    '#type' => 'textfield',
    '#title' => t('Last name'),
    '#value' => $lastname,
    '#required' => TRUE,
  );
  $form['name']['year_of_birth'] = array(
    '#type' => 'textfield',
    '#title' => "Year of birth",
    '#description' => 'Format is "YYYY"',
    '#value' => $birthyear,
    '#required' => TRUE,
  ); 

    // Image upload field.
   $form['name']['image'] = array(
    '#type' => 'managed_file',
    '#title' => 'File',
    '#upload_location' => 'public://my-files/',
    '#process' => array('formuserentry_my_file_element_process'),
    "#upload_validators"  => array('file_validate_is_image' => array())
  );



  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Submit',
  );
  return $form;

}

/*********  for validation ************/

> function formuserentry_my_file_element_process($element, &$form_state,
> $form) {   $element = file_managed_file_process($element, $form_state,
> $form);   $element['upload_button']['#access'] = FALSE;   return
> $element; }
> 
> function formuserentry_application_validate($form, &$form_state) {  
> $year_of_birth = $form_state['values']['year_of_birth'];
>     if ($year_of_birth && ($year_of_birth < 1900 || $year_of_birth > 2000)) {
>         form_set_error('year_of_birth', 'Enter a year between 1900 and 2000.');
>     } }

/********** form submission ***************/

    function formuserentry_application_submit($form, &$form_state) {
        $first_name    = $form_state['values']['first']; 
        $last_name     = $form_state['values']['last'];
        $year_of_birth = $form_state['values']['year_of_birth'];
        $profileimage      = $form_state['values']['image'];

        $canid      = $form_state['values']['canid'];

        if($canid == '') {
            $nid = db_insert('userentryform')
                  ->fields(array(
                    'firstname' => $form_state['values']['first'],
                    'lastname' => $form_state['values']['last'],
                    'birthyear' => $form_state['values']['year_of_birth'],
                    'profileimage' =>  $form_state['values']['profileimage'],
                  ))
                  ->execute(); 
            drupal_set_message(t('The form has been Added your last insert ID is => '.$nid));     
        } else {


        $nid = db_update('userentryform')
                  ->fields(array(
                    'firstname' => $form_state['values']['first'],
                    'lastname' => $form_state['values']['last'],
                    'birthyear' => $form_state['values']['year_of_birth']
                  ))
                  ->condition('userentryId',$canid)
                  ->execute(); 
        drupal_set_message(t('The form has been Updated your last insert ID is => '.$nid));

        }
        drupal_goto("/formuserentry/");





    }

php - Drupal 7 adding custom menus to pages - Stack Overflow

php drupal drupal-7 drupal-modules drupal-menu
Rectangle 27 0

@using (Html.BeginForm("Upload", "Pictures", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.AntiForgeryToken()
    <div>
    Title:<br/>
    @Html.EditorFor(x => x.Title)<br/>
    @Html.ValidationMessageFor(x => x.Title)<br/>
    @Html.TextBoxFor(x => x.File, new { 
    type = "file"
    })<br/> 
    @Html.ValidationMessageFor(x => x.File)<br/> 
    Description:<br/>
    @Html.TextAreaFor(x => x.Description)<br/>
    @Html.ValidationMessageFor(x => x.Description)
    </div>
    <div style="clear:both"></div>
    <p><input type="submit" value="Save"/></p>
}
public class UploadModel
    {
        [Required(ErrorMessage=("You have not selected a file"))]
        public HttpPostedFileBase File { get; set; }
        [Required(ErrorMessage = "Please enter a title")]
        [StringLength(50)]
        public string Title { get; set; }
        [StringLength(400)]
        public string Description { get; set; }
    }
[Authorize(Roles = "Approved")]
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Upload(UploadModel m)
    {
        byte[] uploadedFile = null;
        Byte123 xxx = new Byte123();
        if (m.File != null && !string.IsNullOrEmpty(m.Title))
        {
            //var fileName = System.IO.Path.GetFileName(m.File.FileName);
            //string c = m.File.FileName.Substring(m.File.FileName.LastIndexOf("."));
           // m.Title = m.Title.Replace(c, "");
            uploadedFile = new byte[m.File.InputStream.Length]; //you get the image as byte here but you can also save it to file.

This is MVC code. If you are using Web Forms then the code should be shorter. I got this from a link but can't find it now so just posted my own code. You also need to make sure that Write permissions are enabled in your host using the Cpanel.

c# - Upload images from ASP.NET to godaddy file system - Stack Overflo...

c# asp.net
Rectangle 27 0

@using (Html.BeginForm("Create", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
    {
        <fieldset>
            <legend>Upload Image</legend>

            @Html.Label("Title")
            @Html.Editor("fileTitle")<br />
            Upload File: <input type="file" name="test" />
            <p>
                <input type="submit" value="Create" />
            </p>
        </fieldset>
    }

    [HttpPost]
            public ActionResult Create(string fileTitle)
            {
                try
                {
                    HttpPostedFileBase file = Request.Files[0];
                    byte[] imageSize = new byte[file.ContentLength];
                    ***file.InputStream.Read(imageSize, 0, (int)file.ContentLength);***
                    Image image = new Image()
                    {
                        Name = file.FileName.Split('\\').Last(),
                        Size = file.ContentLength,
                        Title = fileTitle,
                        ID = 1,
                        Image1 = imageSize
                    };
                    db.Images.AddObject(image);
                    db.SaveChanges();
                    return RedirectToAction("Detail");
                }
                catch(Exception e)
                {
                    ModelState.AddModelError("uploadError", e);
                }
                return View();
            }

asp.net - Image Upload, Conversion Error InputStream.Read() method - S...

asp.net asp.net-mvc