java file Upload, download, delete implementation code

Source: Internet
Author: User

Recently did an attachment upload download delete function, specially to record the key code down, convenient for later reuse, but also share to everyone!

The first is the JSP code:

        <TD class= "tdHead33" > Accessories upload: <br/><font color= "Red" ><b> (hint: Single file upload must not exceed 10M) </b></ font></td> <td id= "accessoryfiletd" ><a onclick= "AddFile ()" > Add accessories </a><br/>                <!--loop out uploaded attachments--                <s:iterator value= "signfilelist"  id= "file"  status= "St1" > <div id= " Accessorydiv<s:property value= "#st1. Index"/> "style=" padding:3px "> <a onclick=" javascript:exportsingle (' <s:property value= ' #file. File_url "/>") "> <s:property value= ' #file. file_name '/>  </a> <a  onclick= "DeleteFile (' accessory ', ' <s:property value= ' #file. File_url "/>", ' <s:property value= ' #st1. Index "/>") "  class=" Edit_button "href=" javascript:void (0); " >         Delete </a>  </div>  </s:iterator>       


Then the JS code:

After the file upload succeeds, the File_url file path saved to the database is the file path + file name + timestamp, delete and download are all determined by File_url.

         var filenum=1;         Add Attachment Upload Control        function AddFile () {var str= "<div id=\" filediv "+filenum+" \ ">" str+= "<input id=\" Accessoryfile\ "name=\" formbean.accessoryfile\ "type=\" file\ "/>"; str+= "<a id=\" delete\ "onclick=\" DeleteFile ("+filenum+") \ "style=\" text-decoration:underline\ "> Delete </a>" $ ("#accessoryFileTd"). Append (str); filenum++ ;   }              <pre name= "code" class= "HTML" >           //delete attachment Upload control   function DeleteFile (num) {$ ("#fileDiv" +num). HTML ("");   

 function DeleteFile (file,id,num) {mini.confirm ("Confirm deleting files on server?", "OK",         & nbsp              function (action) {                              if (action = = "OK") {                & nbsp;                        $.post (                                             bootpath+ "/ajax3/uploadfile_deletefile.action",                                            {"Appattachmentid":id},                                             function (data, textstatus) {                                                                                                      if (data.result== "Success")                                                     {                                                      $ ("#accessoryDiv" +num). HTML ("");                                                      mini.alert ("Delete succeeded!");                                                      }                              &nbsp                     else                                                   {                                                          mini.alert ("Operation failed!");                                                          return;                                                     }                                           }, "JSON" );                                                     }                        }                      ); }
This is the download of the attachment JS, where Appattachmentid is the attachment path
function Exportsingle (appattachmentid) {             var url =   bootpath+ "/inner/uploadfile_downloadfile.action? Appattachmentid= "+appattachmentid;   $ ("#actionForm"). attr ("action", URL). Submit ();        


Then the Java code:

To upload an attachment to a server, you first need to create a folder that holds the attachment:

Public final static String File_path = "Upload";  

It then passes two parameters to the calling method: the file name and the file path.

private void Uploadingfileinnersigninfo (map map) throws Exception {String personId = map.get ("PersonId"). ToString (); String Pactid = Map.get ("Pactid"). ToString (); if (""!=map.get ("Accessoryfilefilename") && null!=map.get ("Accessoryfilefilename") && "!=map.get (" Accessoryfile ") && null!=map.get (" Accessoryfile ")) {String accessoryfilefilename = Map.get (" Accessoryfilefilename "). ToString (); String accessoryfile = Map.get ("Accessoryfile"). ToString ();        string[] files = Accessoryfile.split (",");         string[] FileNames = Accessoryfilefilename.split (",");         for (int i = 0; i < files.length; i++) {Fileparam param = new Fileparam ();    String FILEURL = Commonconstant.file_path + "/" + Filenames[i] + datetool.getcurrrentdate2 ();    Param.setpactid (Pactid);                 Param.setfilename (Filenames[i]);                Param.setcreatedby (PERSONID);                Param.setlastupdateby (PERSONID); Param.setcreationdate (Datetool.getcurrrentdate1 ());                Param.setlastupdateddate (Datetool.getcurrrentdate1 ());        Uploadingfile (Files[i], Commonconstant.file_path, filenames[i], param); }}  }
   /** * Upload File Method * @return */public boolean uploadingfile (string files, string folderName, Strin            G Paramfilename, Fileparam Fileparam) throws Exception {if (files = = NULL | | paramfilename = NULL) {        return false;        } String Currentdatestr = Datetool.getcurrrentdate2 ();                String name = Fileutil.getfilename (paramfilename) + "_" + Currentdatestr + "."        + Fileutil.getextentionname (paramfilename);        FileOutputStream fos = null;        FileInputStream FIS = null;            try {String FolderPath = This.getserverfilepath (folderName);            File Folderfile = new file (FolderPath);            if (!folderfile.exists ()) {Folderfile.mkdir ();            FIS = new FileInputStream (files);            FOS = new FileOutputStream (folderpath + "\ \" + name);            byte[] buffer = new byte[102400];       int len = 0;     while (len = fis.read (buffer)) > 0) {fos.write (buffer, 0, Len);            } fileparam.setfileurl (FolderName + "/" + name); String sql = "INSERT into Pact_baseinfo_inner_signfile (pact_id,file_name,file_url,creation_date,created_by,last_               update_date,last_updated_by) "; SQL + = "VALUES ('" + fileparam.getpactid () + "', '" +fileparam.getfilename () + "', '" +fileparam.getfileurl () + "', Sysdate, '"                              +fileparam.getcreatedby () + "', Sysdate, '" +fileparam.getlastupdateby () + "')";                    Pactbaseinfoinnersigndao.executesql (SQL);            } catch (Exception e) {//e.printstacktrace ();        return false;        } finally {close (FOS, FIS);    } return true; }/** * Close file Stream objects * * @param fos * @param fis */private void Close (FileOutputStream fos, Fi Leinputstream fis) {if (FIS! = null) {           try {fis.close ();            } catch (IOException e) {e.printstacktrace ();                }} if (FOS! = null) {try {fos.flush ();            Fos.close ();            } catch (IOException e) {e.printstacktrace ();    }}}/** * Get the detailed path of the uploaded file * @return */public string Getserverfilepath (string folderName) {String basepath = Servletactioncontext.getrequest (). GetSession (). Getservletconte        XT (). Getrealpath ("");    return basepath + "\ \" + FolderName; }

Deletion and download of key code

public class Uploadfileaction {private Uploadfileservice uploadfileservice;private String filename;private InputStream Inputstream;private string Appattachmentid;private String realpath = Servletactioncontext.getservletcontext (). Getrealpath ("/");p rivate Map resultmap=new HashMap ();                        Public String DownLoadFile () {try{map fp = uploadfileservice.queryfilerecordindb (Appattachmentid); Before downloading, determine whether the file exists in the database  if (null! = FP) {fileName = (String) fp.get ("file_name");                                String Path = Realpath + fp.get ("File_url");                               "\" in the path to the foreground will be considered an escape character, so save the "/" when saved, which is required to be replaced as a parameter in the background.  path = Path.replaceall ("/", "\\\\"); InputStream = new FileInputStream (path); }catch (Exception e) {e.printstacktrace ();}    return "DownLoad";                       If dir is an absolute path}public String DeleteFile () {try{map fp = uploadfileservice.queryfilerecordindb (Appattachmentid);               <pre name= "code" class= "HTML" >         Before downloading, determine if the file exists in the database 
if (null! = FP) {String path = (string) fp.get ("File_url");
UPLOADFILESERVICE.DELETEFILERECORDINDB (path);
"\" in the path to the foreground will be considered an escape character, so save the "/" when saved, which is required to be replaced as a parameter in the background.
Path = Path.replaceall ("/", "\\\\"); String FolderPath = Getserverfilepath (Commonconstant.file_path). Replace (Commonconstant.file_path, "");p ath = FolderPath +path;uploadfileservice.deletefileinserver (path); }resultmap.put ("Result", "success");} catch (Exception e) {resultmap.put ("result", "error");} Return "Success";}
}


You need to check the attachment size before uploading, do not exceed 10M.

@Override    Public  boolean isoversize (file file, int size)    {        if (file = = NULL | |!file.exists ())        {            return false;        }        FileInputStream FIS = null;        Try        {            double fileSize = file.length ()/1000000.0;                        if (fileSize <= size)            {                return false;            }            else            {                return true;            }                    }        catch (Exception e)        {            e.printstacktrace ();            return false;        }        Finally        {            if (FIS! = null)            {                try                {                    fis.close ();                }                catch (IOException e)                {                    e.printstacktrace ();                }        }}            }







java file Upload, download, delete implementation code

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.