Seeking file upload help.

Hi,
This has been frustrating me severely of late.  I have two pages that visitors of my site shall go to for uploading photos.  The first page is a simple two question form asking them to enter how many photos will they be uploading in a text field as well as a select drop down of recent dates for which their pictures pertain to. Once those questions are answered and a visitor hits submit, the next page contains the total number of browse dialogue boxes for the # of photos that they intend to submit. Keep in mind that each person is meant to upload photos for just one day at a time and their uploads will go to a specific folder for that date.   I've passed the value of $_POST['selct_dates'] to a variable on the second page like $date = $_POST['selct_dates'] and tried appending this value to what has been defined as the top level 'uploads' folder. So the defined pathway is this... define('SOURCE_DIR', 'C:\inetpub\wwwroot\mysite\images\\'.$date.'\\');
Then to upload the files I should be able to do this...
$file = ($_FILES['image']['name']);
if (array_key_exists('upload', $_FILES) {
define('SOURCE_DIR', 'C:\inetpub\wwwroot\mysite\images\\'.$date.'\\');
          foreach ($file as $number => $file) { 
$success = move_uploaded_file($_FILES['image']['tmp_name'][$number],SOURCE_DIR.$file); } }
So upon upload, the file(s) would go to SOURCE_DIR.$date while the $file variable may be appended to this pathway,.right?
there's actually one more foreach loop included in my actual code due to my select form element having been built as a looped array such as
/*   echo '<option value="' . $option . '"';
if (in_array($option, $date)) {
  echo " selected";
echo ">" . ucfirst($option) . "</option>"; */ but that's a bit more complicated....
So anyway my trouble has been that the SOURCE_DIR is set as it should be when the visitor first goes to the second page.  But after hitting 'upload' photos on the submit button as the final step, the SOURCE_DIR is no longer the pathway when echoing $var = $SOURCE_DIR.$date.  But rather it echos SOURCE_DIR\some_date.  For example when I first navigate initially to the file selection page 2 from the questionaire page 1, I can echo that SOURCE_DIR.$date equals the pathway C:\inetpub\wwwroot\mysite\uploads\06_01\ . However after a visitor hits the submit button the page refreshes and the echo is SOURCE_DIR\06_01\
Essentially the SOURCE_DIR isn't retaining it's value as a pathway but rather takes on the literal string. Hence the photos are not making it to their desired directory. How can I make the SOURCE_DIR constant remain set all the way through the visitor hitting submit?   Thank you.

You might find it more helpful to post in a forum which is at least marginally relevant to the question. I don't see any XML content at all in that question.

Similar Messages

  • File Upload Help Needed - Very Urgent

    Dear All
    I am making a application in Webdynpro for uploading an excel file to the server. Can someone give me a demo application so that I can run it and see whether my server is configured or not. Also I have made the application right now and have coded the need full. But when I select a file and say submit it shows me a page not found error. Currently I am working round the clock on my project and am stuck up here. Its very urgent can any body help please with an example or a demo application.
    Regards Gaurav

    Hi,
      Check whether in server, MultipartBodyParameterName property is set to "com.sap.servlet.multipart.body" . You can check this by going to Visual Admin -> Cluster tab -> Services -> web container -> Properties sheet.
    Do assign points if i answered your question.
    Regards
    Vasu

  • Desperatly seeking file conversion help!

    I had a photo scanned and it's in pdf format. How do i convert it to a jpeg? or similar file? The website where I am trying to upload it will not take pdf. I use adobe 7.0
    help!

    Graffiti..
    You are spot on! The pdf converter worked great!
    Now I have to try to figure out how to crop it. I'll need to contact adobe since my photoshop...which I have never used...apparently has a corrupted file.Errrrrrr.
    But I am gratful to you for your very helpful answer and VERY prompt resonse. thankyou again!

  • J2me multipart file upload-  Help Needed

    package com.mpbx;
    import javax.microedition.midlet.*;
    import javax.microedition.lcdui.*;
    import javax.microedition.io.*;
    import java.io.*;
    public class PostFile extends MIDlet implements Runnable, CommandListener{
        private final String FILE = "/image.jpg";
        private final String URL = "http://localhost/post.php"; // change this to a valit page.
        private final String CrLf = "\r\n";
        private Form form = null;
        private Gauge gauge = null;
        private Command exitCommand;
        private Command uploadCommand;
        public PostFile(){
            form = new Form("Upload File");
            gauge = new Gauge("Progress:", true, 100, 0);
            form.append(gauge);
            exitCommand = new Command("Exit", Command.EXIT, 0);
            uploadCommand = new Command("Upload", Command.SCREEN, 0);
            form.addCommand(exitCommand);
            form.addCommand(uploadCommand);
            form.setCommandListener(this);
        public void startApp() {
            Display.getDisplay(this).setCurrent(form);
        public void pauseApp() {
        public void destroyApp(boolean unconditional) {
        private void progress(int total, int current){
            int percent = (int) (100 * ((float)current/(float)total));
            gauge.setValue(percent);
        public void run() {
            httpConn();
        private void httpConn(){
            HttpConnection conn = null;
            OutputStream os = null;
            InputStream is = null;
            try{
                System.out.println("url:" + URL);
                conn = (HttpConnection)Connector.open(URL);
                conn.setRequestMethod(HttpConnection.POST);
                String postData = "";
                InputStream imgIs = getClass().getResourceAsStream(FILE);
            byte []imgData = new byte[imgIs.available()];
               imgIs.read(imgData);
                String message1 = "";
                message1 += "-----------------------------4664151417711" + CrLf;
                message1 += "Content-Disposition: form-data; name=\"uploadedfile\"; filename=\"" + FILE + "\"" + CrLf;
                message1 += "Content-Type: image/jpeg" + CrLf;
                message1 += CrLf;
                // the image is sent between the messages ni the multipart message.
                String message2 = "";
                message2 += CrLf + "-----------------------------4664151417711--" + CrLf;              
                conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=---------------------------4664151417711");
                // might not need to specify the content-length when sending chunked data.
                // conn.setRequestProperty("Content-Length", String.valueOf((message1.length() + message2.length() + imgData.length)));
                System.out.println("open os");
                os = conn.openOutputStream();
                System.out.println(message1);
                os.write(message1.getBytes());
                // SEND THE IMAGE
                int index = 0;
                int size = 1024;
                do{
                    System.out.println("write:" + index);
                    if((index+size)>imgData.length){
                        size = imgData.length - index;
                    os.write(imgData, index, size);
                    index+=size;
                    progress(imgData.length, index); // update the progress bar.
                }while(index<imgData.length);
                System.out.println("written:" + index);           
                System.out.println(message2);
                os.write(message2.getBytes());
                os.flush();
                System.out.println("open is");
                is = conn.openInputStream();
                char buff = 512;
                int len;
                byte []data = new byte[buff];
                do{
                    System.out.println("READ");
                    len = is.read(data);
                    if(len > 0){
                        System.out.println(new String(data, 0, len));
                }while(len>0);
                System.out.println("DONE");
            }catch(Exception e){
                e.printStackTrace();
            }finally{
                System.out.println("Close connection");
                try{
                    os.close();
                }catch(Exception e){}
                try{
                    is.close();
                }catch(Exception e){}
                try{
                    conn.close();           
                }catch(Exception e){}
        public void commandAction(javax.microedition.lcdui.Command command, javax.microedition.lcdui.Displayable displayable) {
            if(command == exitCommand){
                this.notifyDestroyed();
            }else if(command == uploadCommand){
                new Thread(this).start();
    }Running this yields the error below...Can someone suggest me. whats the problem.
    url:http://localhost/post.php
    java.lang.NullPointerException
            at com.mpbx.PostFile.httpConn(PostFile.java:85)
            at com.mpbx.PostFile.run(PostFile.java:68)
    Close connection

    I also faced the same problem. To make this code work you will have to include the image.jpg in the jar. To do that, copy the image file in the src directory inside your project folder (if you are using netbeans) and then build the project.
    Remember, the web server should be running in background.

  • Flat FIle Upload Help!

    Hi, I will have a unix directory of 10-20 text files with different names, but same structure that I need to load into BW.  The directory will have any number of files with different names and they all need to be loaded.  How can I come up with a solid process to load these files? 
    I thought just calling an ABAP program to loop through the file names and execute the same DTP somehow using a different file name?  Is this possible?  Any thorough help is greatly appreciated.
    Thanks,
    Ken Murray

    Kenneth,
        Good Question!
        on the External Data Tab Page, we haev one option "<b>Create Routine</b>". We can use that option to dynamically generate the File Name. Still we need to have several Infopackages to load the data. i don't see any advantage creating this. This routine will be useful if the file name varies based on some criteria. not to process all the files in directory. for that we need to process Infopackages those many times.
    Keep all the file Names in a Table rather than DSO.
    In my view, instead of using Infopackges. Try creating an ABAP program and read the File Names which you saved in Transparent Table(all 30 files in to Internal Tables). Call the Funcion Module (BAPI_IPAK_CHANGE) to schedule the Infopackage for 30 times using different Names. then one infopackage will be sufficient.
    all the best.
    Regards,
    Nagesh Ganisetti.

  • HELP! File Upload Servlet and Internet Explorer

    Hello people. I hope this is an easy problem to solve...
    I have a servlet upload program that works using Mozilla browser (www.mozilla.org), but for some reason it doesn't work using Microsoft IE. The servlet is also using the servlet upload API from Apache (commons).
    I'm using IE version 6.0.2800.1106 in a Win98SE host computer. I get a cannot find path specified error message (see below). At work, I also get the same error message using IE, but don't know what version. The OS is XP. Unfortunately, at work, I can't install Mozilla browser (or any software-company policy) to see if Mozilla works there too. I would've like to have tested to see if the upload program worked on Mozilla on a truly remote computer.
    So I figured, it must be a IE configuration issue, but darn it!! I began by resetting IE to default settings, but still have the problem, I played around with several different combinations of settings in "Tools"-->"Internet Options...", and I still get the error message. Someone PLEASE HELP ME!!!
    Dunno, if it will help, I've also pasted the upload servlet source code below and the html file that's calling the upload servlet, but you still need the Apache commons file upload API.
    Trust me on this one folks, for some reason it works for Mozilla, but not for IE. With IE, I can at least access web server, and therefore, the html file that calls the upload servlet , so I don't think it's a Tomcat configuration issue (version 5.0). I actually got the code for the file upload servlet from a book relatively new in the market (printed in 2003), and it didn't mention any limitations as far as what browser to use or any browser configuration requirements. I have e-mailed the authors, but they probably get a ton of e-mails...
    Anyone suggestions?
    Meanwhile, I will try to install other free browsers and see if the file upload program works for them too.
    ERROR MESSAGE:
    "HTTP Status 500 -
    type Exception report
    message
    description The server encountered an internal error () that prevented it from fulfilling this request.
    exception
    javax.servlet.ServletException: C:\TOMCAT\webapps\MyWebApps\files\C:\WINDOWS\Desktop\myfile.zip (The system cannot find the path specified)
         com.jspbook.FileUploadCommons.doPost(FileUploadCommons.java:43)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:763)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:856)
    root cause
    java.io.FileNotFoundException: C:\TOMCAT\webapps\MyWebApp\files\C:\WINDOWS\Desktop\myfile.zip (The system cannot find the path specified)
         java.io.FileOutputStream.open(Native Method)
         java.io.FileOutputStream.(FileOutputStream.java:176)
         java.io.FileOutputStream.(FileOutputStream.java:131)
         org.apache.commons.fileupload.DefaultFileItem.write(DefaultFileItem.java:392)
         com.jspbook.FileUploadCommons.doPost(FileUploadCommons.java:36)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:763)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:856)
    note The full stack trace of the root cause is available in the Tomcat logs.
    Apache Tomcat 5.0.16"
    FILE UPLOAD SERVLET source code:
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import org.apache.commons.fileupload.*;
    import java.util.*;
    public class FileUploadCommons extends HttpServlet {
    public void doPost(HttpServletRequest request,
    HttpServletResponse response)
    throws IOException, ServletException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    out.println("<html>");
    out.print("File upload success. <a href=\"/MyWebApp/files/");
    out.print("\">Click here to browse through all uploaded ");
    out.println("files.</a><br>");
    ServletContext sc = getServletContext();
    String path = sc.getRealPath("/files");
    org.apache.commons.fileupload.DiskFileUpload fu = new
    org.apache.commons.fileupload.DiskFileUpload();
    fu.setSizeMax(-1);
    fu.setRepositoryPath(path);
    try {
    List l = fu.parseRequest(request);
    Iterator i = l.iterator();
    while (i.hasNext()) {
    FileItem fi = (FileItem)i.next();
    fi.write(new File(path, fi.getName()));
    catch (Exception e) {
    throw new ServletException(e);
    out.println("</html>");
    public void doGet(HttpServletRequest request,
    HttpServletResponse response)
    throws IOException, ServletException {
    doPost(request, response);
    HTML PAGE that calls the upload servlet:
    <html>
    <head>
    <title>Example HTML Form</title>
    </head>
    <body>
    <p>Select a file to upload or browse
    currently uploaded files.</p>
    <form action="http://##.##.##.####/MyWebApp/FileUploadCommons"
    method="post" enctype="multipart/form-data">
    File: <input type="file" name="file"><br>
    <input value="Upload File" type="submit">
    </form>
    </body>
    </html>
    Thanks in advance for any assistance.
    -Dan

    I'm guessing what is happening is that Mozilla tells the servlet "here comes the file myfile.zip". The servlet builds a file name for it:
        String path = sc.getRealPath("/files");
        // path is now C:\TOMCAT\webapps\MyWebApps\files\
        fi.write(new File(path, fi.getName()));
        // append myfile.zip to "path", making it C:\TOMCAT\webapps\MyWebApps\files\myfile.zipIE, however, tells "here comes the file C:\WINDOWS\Desktop\myfile.zip". Now imagine what the path+filename ends up being...
    So what you want to do is something along the lines of (assuming Windoze):
    public static String basename(String filename)
        int slash = filename.lastIndexOf("\\");
        if (slash != -1)
            filename = filename.substring(slash + 1);
        // I think Windows doesn't like /'s either
        int slash = filename.lastIndexOf("/");
        if (slash != -1)
            filename = filename.substring(slash + 1);
        // In case the name is C:foo.txt
        int slash = filename.lastIndexOf(":");
        if (slash != -1)
            filename = filename.substring(slash + 1);
        return filename;
        fi.write(new File(path, basename(fi.getName()));
        ....You can make the file name check more bomb proof if security is an issue. Long file names trying to overflow something in the OS, NUL characters, Unicode, forbidden names in Windos (con, nul, ...), missing file name, ...

  • File upload on different server. URGENT need help.

    hi,
    I am using struts common file upload to upload file from client. My problem is my application is running on server A but i want to store uploaded stream on server B without storing it on server A(i,e. without using FTP or rsync from server A to server B). Please help how can i achieve this task.
    Anuj

    Write and run a standalone application on "Server A" to accept a socket connection from "Server B" then feed the inputStream that "Server B" uses to upload the file, to the socketOutputStream that it has opened with "Server A" and have Server A save that file.

  • Problem with Multi File upload example, help needed

    I got the code from the following location.....
    http://www.adobe.com/devnet/coldfusion/articles/multifile_upload.html
    And I've got it to work to some degree except I cant get the file transfer to work when pressing, Upload.   Below is what my debugger outputs.  Any thoughts on how to fix this or even what it means?
    At the very bottom of this message is the upload.cfm code.......
    Thanks in advance for the help
    <html>
    <head>
      <title>Products - Error</title>
    </head>
    <body>
    <h2>Sorry</h2>
    <p>An error occurred when you requested this page.
    Please email the Webmaster to report this error.
    We will work to correct the problem and apologize
    for the inconvenience.</p>
    <table border=1>
    <tr><td><b>Error Information</b> <br>
      Date and time: 12/07/09 22:25:51 <br>
      Page:  <br>
      Remote Address: 67.170.79.241 <br>
      HTTP Referer: <br>
      Details: ColdFusion cannot determine how to process the tag &lt;CFDOCUMENT&gt;. The tag name may be misspelled.<p>If you are using tags whose names begin with CF but are not ColdFusion tags you should contact Allaire Support. <p>The error occurred while processing an element with a general identifier of (CFDOCUMENT), occupying document position (41:4) to (41:70).<p>The specific sequence of files included or processed is:<code><br><strong>D:\hshome\edejham7\edeweb.com\MultiFileUpload\upload.cfm      </strong></code><br>
      <br>
    </td></tr></table>
    </body>
    </html>
    <!---
    Flex Multi-File Upload Server Side File Handler
    This file is where the upload action from the Flex Multi-File Upload UI points.
    This is the handler the server side half of the upload process.
    --->
    <cftry>
    <!---
    Because flash uploads all files with a binary mime type ("application/ocet-stream") we cannot set cffile to accept specfic mime types.
    The workaround is to check the file type after it arrives on the server and if it is non desireable delete it.
    --->
        <cffile action="upload"
                filefield="filedata"
                destination="#ExpandPath('\')#MultiFileUpload\uploadedfiles\"
                nameconflict="makeunique"
                accept="application/octet-stream"/>
            <!--- Begin checking the file extension of uploaded files --->
            <cfset acceptedFileExtensions = "jpg,jpeg,gif,png,pdf,flv,txt,doc,rtf"/>
            <cfset filecheck = listFindNoCase(acceptedFileExtensions,File.ServerFileExt)/>
    <!---
    If the variable filecheck equals false delete the uploaded file immediatley as it does not match the desired file types
    --->
            <cfif filecheck eq false>
                <cffile action="delete" file="#ExpandPath('\')#MultiFileUpload\uploadedfiles\#File.ServerFile#"/>
            </cfif>
    <!---
    Should any error occur output a pdf with all the details.
    It is difficult to debug an error from this file because no debug information is
    diplayed on page as its called from within the Flash UI.  If your files are not uploading check
    to see if an errordebug.pdf has been generated.
    --->
            <cfcatch type="any">
                <cfdocument format="PDF" overwrite="yes" filename="errordebug.pdf">
                    <cfdump var="#cfcatch#"/>
                </cfdocument>
            </cfcatch>
    </cftry>

    Just 2 things in my test:
    1) I use no accept attribute. Coldfusion is then free to upload any extenstion.
    Restricting the type to application/octet-stream may generate errors. Also, it is unnecessary, because we perform a type check anyway.
    2) I have used #ExpandPath('.')#\ in place of #ExpandPath('\')#
    <cfif isdefined("form.filedata")>
    <cftry>
    <cffile action="upload"
                filefield="filedata"
                destination="#expandPath('.')#\MultiFileUpload\uploadedfiles\"
                nameconflict="makeunique">
            <!--- Begin checking the file extension of uploaded files --->
            <cfset acceptedFileExtensions = "jpg,jpeg,gif,png,pdf,flv,txt,doc,rtf"/>
            <cfset filecheck = listFindNoCase(acceptedFileExtensions,File.ServerFileExt)/>
    <!---
    If the variable filecheck equals false delete the uploaded file immediatley as it does not match the desired file types
    --->
            <cfif filecheck eq false>
                <cffile action="delete" file="#ExpandPath('.')#\MultiFileUpload\uploadedfiles\#File.ServerFile#"/>
                <cfoutput>Uploaded file deleted -- unacceptable extension (#ucase(File.ServerFileExt)#)</cfoutput>.<br>
            </cfif>
    Upload process done!
            <cfcatch type="any">
                There was an error!
                <cfdocument format="PDF" overwrite="yes" filename="errordebug.pdf">
                    <cfdump var="#cfcatch#"/>
                </cfdocument>
            </cfcatch>
    </cftry>
    <cfelse>
    <form method="post" action=<cfoutput>#cgi.script_name#</cfoutput>
            name="uploadForm" enctype="multipart/form-data">
            <input name="filedata" type="file">
            <br>
            <input name="submit" type="submit" value="Upload File">
        </form>
    </cfif>

  • Help with File Upload manually

    Hi Experts,
    I need code to upload a file without using the upload UI Element. we have our terms and conditions which has to be signed by the user and once the user signs and clicks the next button to go to the next page, I generate a pdf with the time stamp of when the user signed and upload it to ECC. here i can not use the File upload UI Element but have to upload it automatically to ECC.
    Can any one help me out with this please.
    Thanks

    Hi,
    I dont know why you need to to upload the file for this requirement. You can simply store the user id and the timestamp in portal database table or in a ECC z table.
    In case you definitely need to upload the file then you can use KM API to uploadthe file to portal KM folder
    http://www.sdn.sap.com/irj/scn/go/portal/prtroot/docs/library/uuid/a099a3bd-17ef-2b10-e6ac-9c1ea42af0e9?quicklink=index&overridelayout=true
    but you need not use the upload feature in the example, instead just get the data from wd context and upload to KM.
    Srini

  • Flash 8 file upload .doc & .pdf help, please

    I've been working with the file upload sample that came with
    Flash 8 as well
    as other sources to help me figure this one out... like:
    http://www.flash-db.com/Tutorials/upload/index.php
    Everything I seem to find out about file uploading with Flash
    specifically
    deals with images, but I need to upload .doc & .pdf files
    to attach to an
    email as part of an employment application process for a site
    that is built
    with Flash.
    The back-end script is a simple ColdFusion file that I've
    tested (and works
    fine with a static HTML test page):
    <cffile action="upload"
    destination = "ServerAddressHERE"
    accept = "image/jpg, application/msword, application/pdf"
    fileField = "Form.resumeFile"
    nameConflict = "Overwrite">
    The Flash example script that comes with Flash 8 has been
    modified as
    follows:
    System.security.allowDomain(" FQDN_here");
    import flash.net.FileReference;
    // The listener object listens for FileReference events.
    var listener:Object = new Object();
    // When the user selects a file, the onSelect() method is
    called, and
    // passed a reference to the FileReference object.
    listener.onSelect = function(selectedFile:FileReference):Void
    // Update the TextArea to notify the user that Flash is
    attempting to
    // upload the image.
    statusArea.text += "Attempting to upload " +
    selectedFile.name + "\n";
    // sample code provided by Flash
    selectedFile.upload("
    http://www.helpexamples.com/flash/file_io/uploadFile.php");
    // my modification here (I have tried absolute references as
    well):
    selectedFile.upload("upfile.cfm");
    listener.onOpen = function(selectedFile:FileReference):Void {
    statusArea.text += "Opening " + selectedFile.name + "\n";
    // Once the file has uploaded, the onComplete() method is
    called.
    listener.onComplete =
    function(selectedFile:FileReference):Void {
    // Notify the user that Flash is starting to download the
    image.
    statusArea.text += "Downloading " + selectedFile.name + " to
    player\n";
    // this part is irrelevant to my needs and I've worked with
    and without it
    imagesCb.addItem(selectedFile.name);
    imagesCb.selectedIndex = imagesCb.length - 1;
    downloadImage();
    var imageFile:FileReference = new FileReference();
    imageFile.addListener(listener);
    uploadBtn.addEventListener("click", uploadImage);
    // this part is irrelevant to my needs and I've worked with
    and without it
    imagesCb.addEventListener("change", downloadImage);
    imagePane.addEventListener("complete", imageDownloaded);
    function imageDownloaded(event:Object):Void {
    if(event.total == -1) {
    imagePane.contentPath = "Message";
    // this part is where I added the extensions I need:
    function uploadImage(event:Object):Void {
    imageFile.browse([{description: "Image Files", extension:
    "*.jpg;*.gif;*.png;*.doc;*.pdf,"}]);
    ANY ideas would be sincerely appreciated... even if it's just
    to confirm
    that the Flash file upload process ONLY works with image
    files.... Thank you
    ALL in advance for ANY help I can get. :-)

    Did you ever get your issue with the F12, publish preview,
    not loading your browser? I have just upgraded from MX 2004 to 8
    and now have this issue.
    T Peluso
    [email protected]

  • Please help me on file upload and download

    Dear all..
    i am new in this i try to apply the tutorial for file upload and download but it is old i work on net weaver 7.1 and many proery has change and i cant applyb this tutorial...

    Thanks. If you can provide some more details about where - some application, or a web page - are you trying to upload or download a file we can discover to documentation you need. Also, it will be of help if you tell what is the name of the outdated guide you mentioned.
    Best regards,
    Rossen

  • I need to select and upload a image and corresponding url from an external website using file upload control in MVC4. Please help

    I need to select and upload a image and corresponding  url from an external website using file upload control in MVC4.
    Please help
    Latheesh K Contact No:+91-9747369936

    This forum supports .NET Framework setup.
    As your issue appears to have nothing to do with .NET Framework setup, please ask in the MVC forums for best support.
    http://forums.asp.net/1146.aspx/1?MVC

  • File Upload - code improvement help

    I have asked similar kind of question before, but it was termed as meaningless. I hope this time it will have some meaning(I am now following the instructions :)).
    I got this code from online, the address is mentioned in the comments. With little changes it is serving the purpose well. However, the upload time is a bit high and I was wondering is there a way to improve that.
    <!-- upload.jsp -->
    <!-- http://forums.codecharge.com/posts.php?post_id=44078 -->
    <html>
        <head>
        <title>Upload Page</title>
        <jsp:useBean class = "formjavabean.application" id = "applicationId" scope = "session" />
        </head>
        <body>
        <%@ page import="java.io.*" %>
        <%
        String userEmail = applicationId.getUserEmail()  ;
        File user = new File("C:\\JBoss\\jboss-4.0.5.GA\\bin\\Fastran\\" + userEmail ) ;
        user.mkdir() ;
        String contentType = request.getContentType();
        System.out.println("Content type is :: " +contentType);
        if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0))
            DataInputStream in = new DataInputStream(request.getInputStream());
            int formDataLength = request.getContentLength();
            byte dataBytes[] = new byte[formDataLength];
            int byteRead = 0;
            int totalBytesRead = 0;
            while (totalBytesRead < formDataLength)
                byteRead = in.read(dataBytes, totalBytesRead, formDataLength);
                totalBytesRead += byteRead;
            String file = new String(dataBytes);
            String saveFile = file.substring(file.indexOf("filename=\"") + 10);
            saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
            saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1,saveFile.indexOf("\""));
            int lastIndex = contentType.lastIndexOf("=");
            String boundary = contentType.substring(lastIndex + 1,contentType.length());
            int pos;
            pos = file.indexOf("filename=\"");
            pos = file.indexOf("\n", pos) + 1;
            pos = file.indexOf("\n", pos) + 1;
            pos = file.indexOf("\n", pos) + 1;
            int boundaryLocation = file.indexOf(boundary, pos) - 4;
            int startPos = ((file.substring(0, pos)).getBytes()).length;
            int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;
            FileOutputStream fileOut = new FileOutputStream("c:\\JBoss\\jboss-4.0.5.GA\\bin\\Fastran\\" + userEmail + "\\" + saveFile);
            fileOut.write(dataBytes, startPos, (endPos - startPos));
            fileOut.flush();
            fileOut.close();
        %>
        <img src="logo.jpeg" width="101" height="75" align = "Right">
        <img src="h_corporate_center.jpg" width="622" height="102">
        <br><br><br><br>
        <b>
        <%
        out.println("File uploaded as "+" \"" +saveFile+" \"");
        %>
        <br><br>
        <b>Please make sure all required files are uploaded:<br>
        <font color = "Red">ftn03, ftn07, and ftn09<font>
        <br><br><br><br>
        <input type=button onClick="location.href='fastran.jsp'" value='Proceed'>
        </body>
    </html>

    the input files are a bunch of text files, with a lot of numbers generated through some other software. There can be some big files (perhaps close to a GB), and the upload time for such a file is painfully long - something like 6 min, over LAN. I have tried to upload it on my own computer(with application server running on it) and for a 50 MB file, it is taking about 3 min.
    There are many third part options are available but that requires some librarires, and this code doesn't. So my preference is for this one.
    Also, I couldn't figure out exactly, but some articles were suggesting to use String buffers instead of just Strings. In my case, Strings are used.
    Secondly, I understand using of input and output buffer stream, but can it be the cause of long upload time? I mean converting a file to some machine independent code and then re-converting it back. If yes, can there be a way of skipping that all together ?
    I am a bit hesitant of asking questions, my previous experience here was not a very pleasant one. Some genius, bullied me around :)
    I will appreciate any help, thanks :)
    Message was edited by:
    NasirMunir

  • Help with file upload

    I was wondering if there's a kind of lightweight component for uploading files in JSF. I tried Oracle's ADF Faces, but besides it being a couple of megs it screwed up the HTML code in my pages and some Javascript functions wouldn't work. I saw a post here where someone created his own component but as it will have minor use in my app i'd like something packed so I can just add it on.
    I only need to upload one file in my app, so maybe it's better to use a regular JSP and Servlet approach for this one. Suggestions or comments would be appreciated, thanks..

    I followed the examples in the chapter, but I needed a .tld file so I created one:
    <?xml version="1.0" encoding="ISO-8859-1" ?>
    <!DOCTYPE taglib
    PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
    "http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
    <taglib>
    <tlib-version>1.0</tlib-version>
    <jsp-version>1.2</jsp-version>
    <short-name>file</short-name>
    <uri>http://java.sun.com/upload</uri>
    <display-name>JSF File Upload</display-name>
    <description>File upload library fo JSF</description>
    <tag>
    <name>upload</name>
    <tag-class>com.corejsf.UploadTag</tag-class>
    <body-content>JSP</body-content>
    <description>
    Uploads the file.
    </description>
    <attribute>
    <name>value</name>
    <required>false</required>
    <rtexprvalue>false</rtexprvalue>
    </attribute>
    <attribute>
    <name>target</name>
    <required>false</required>
    <rtexprvalue>false</rtexprvalue>
    </attribute>
    </tag>
    </taglib>
    Its in WEB-INF and declared in web.xml, but I'm getting an error:
    javax.faces.FacesException: Expression Error: Named Object: 'com.corejsf.Upload' not found.
    There's no such class in the component, but the UploadTag returns "com.corejsf.Upload" in both getRenderedType() and getComponentType().
    If someone has this working; help please!!

  • Help with file upload Actionscript

    I am trying to do a file upload using Actionscript and a
    modified version of the tutorial found at:
    http://tutorials.lastashero.com/2005/10/creating_a_file_upload_applica.html
    When I call the function
    fileRef.upload("
    http://www.imgthis.com/upload_loader.php");
    should that go to that page once it finishes, or how do I
    force Flash to redirect the browser to that page passing the
    uploaded file?
    What am I missing here, or what else would anyone need to
    help me?
    Any help would be greatly appreciated thanks in advance!
    Joshua Abts

    It seems as though the page is not being loaded after the
    ActionScript upload command.
    Why would my PHP script not be called from the upload
    ActionScript? I even just did a simple one line redirect to see if
    the PHP script was even being called and it didn't work.
    What is the basis for getting the script to send the picture
    to the PHP script as a post and using the $_FILES array?
    Thanks,
    Josh

Maybe you are looking for

  • Custom splash screen on infoview 3.1

    Hi. Does anyone have any quick tips on how to modify the home InfoView "Home Page" after logging in? Our team needs to post a table of announcements and important maintenance updates directly below the "Navigate" section. I see that under the \Busine

  • When organizing my bookmark folders I accidentally dragged one off screen and it disappeared. How do I get it back?

    I was moving folders around and one got dragged off screen. I let go of the mouse and it disappeared. I tried to undo the move but the option was not available. When I go to save a bookmark, the option for the folder is still there, but in the bookma

  • Ca I create in Discoverer Administration a variable count ??

    I want to view on discoverer only products which have a price for modelize tenders. So I calculated for a view the number of products which have a price and I kept then only products which have the maximum for the count To resume I want an item that

  • Maintain value for condition type

    Hi All How can i maintain fix value for any condition type so that while creating PO it will automatically picked in PO. e.g I want to maintain CVD as 16% usefull ans will be rewarded rajesh

  • Kindle App not working with yosemite

    Hi All. After I downloaded the new Yosemite. I had a notice that said my free kindle app downloaded from amazon is not supported by Yosemite. I Have lots of books stored in this app and I need to know is this down to Apple to fix or should I complain