Upload file Function-1

Source: Internet
Author: User
Tags readfile

Effect:

Code: JSP
<liclass="Item db"> <spanclass="tt">pos Document:</span> <Div class="File-line"> <formID="DataForm"action="${ctx}/uploadfilesftp"Enctype="Multipart/form-data"Method="POST"> <input type="Text" ID="Viewfile"onmouseout="document.getElementById (' file '). style.display= ' None ';" class="Inputstyle"/> <label for="Unload"Onmouseover="document.getElementById (' file '). style.display= ' block ';" class="File1"></label> <input type="File" name="File"Onchange="document.getElementById (' Viewfile '). value=this.value;this.style.display= ' None '; Autouploadfile ()" class="File" ID="File"/> </form> </Div> </li>
Js:
 function autouploadfile() {if(Uploadfilecheck ()) {        $(' #dataform '). Ajaxsubmit ({dataType:' JSON ', Success: function(data) {if(Data.Error! = null && typeof (data.Error) !="undefined") {Alert (data.Error); }Else{filepaths = Data.info;                alert (data.msg);            }; },Error: function(status, err) {Console.info (status+","+ERR); Alert"Status:"+status+"ERR:"+ERR); }        })    }}
 function uploadfilecheck(){     varUpload_file = $ (' #viewfile '). Val ();varFileTypes =New Array("POS","TXT");varFiletypeflag ="0";if(Upload_file! =""){varNewFileName = Upload_file.split ('. '); NewFileName = newfilename[newfilename.length-1]; for(varI=0; i<filetypes.length;i++) {if(Filetypes[i] = = NewFileName) {Filetypeflag ="1"; }         };if(Filetypeflag = ="0") {alert ("Upload file must be pos, txt format drops");return false; };return true; }Else{Alert ("Please upload the file!" ");return false; }       }
Java
Packagecom. Tydic. Unicom. Res. Web. Busi. Controller. Rescard;Import Java. IO. BufferedReader;Import Java. IO. IOException;Import Java(i). InputStream;Import Java. IO. InputStreamReader;Import Javax. servlet. HTTP. HttpServletRequest;Import Javax. servlet. HTTP. HttpServletResponse;Import Javax. servlet. HTTP. HttpSession;Import Net. SF. JSON. Jsonobject;import org. Apache. Log4j. Logger;import org. Springframework. Stereotype. Controller;import org. Springframework. Web. Bind. Annotation. Requestmapping;import org. Springframework. Web. Bind. Annotation. Requestmethod;import org. Springframework. Web. Bind. Annotation. Responsebody;import org. Springframework. Web. Multipart. Multipartfile;import org. Springframework. Web. Multipart. Multiparthttpservletrequest;Importcom. Jcraft. Jsch. Channelsftp;Importcom. Jcraft. Jsch. Jschexception;Importcom. Jcraft. Jsch. Sftpexception;Importcom. Tydic. Unicom. Res. Web. Busi. Controller. config. GetToken;Importcom. Tydic. Unicom. Res. Web. Busi. Controller. config. Sftpchannelutil;@Controllerpublic class Fileuploadsftpcontroller {private static Logger Logger = Logger. GetLogger(Fileuploadsftpcontroller. Class); @RequestMapping (value="/uploadfilesftp", Method=requestmethod. POST) @ResponseBody public void uploadfilesftp (Multipartfile file,httpservletrequest request,httpservletresponse respons E,httpsession session) throws IOException, Jschexception, sftpexception{jsonobject jsonout = new Jsonobject ();Request. setcharacterencoding("Utf-8");Response. setcharacterencoding("Utf-8");String FilePath = null;if (Request instanceof Multiparthttpservletrequest) {if (file. IsEmpty()) {Logger. Info("File not uploaded");Jsonout. Put("Error","Upload file content is empty");Response. setContentType("Text/html;charset=utf-8");Response. Getwriter(). Print(Jsonout. toString());}else{Logger. Info("Upload file content information:"+readfile (file. getInputStream()));if (IsValid (readFile (file. getInputStream())) {Sftpchannelutil channel = new Sftpchannelutil ();Channelsftp channelsftp = Channel. Getchannel(60000);FilePath = GetToken. Get("Sftp_req_loc")+"/"+file. Getoriginalfilename();Logger. Info("File Upload path:"+filepath);Channelsftp. Put(File. getInputStream(), FilePath, channelsftp. OVERWRITE);Session. SetAttribute("FilePath", FilePath);Request. SetAttribute("FilePath", FilePath);Jsonout. Put("MSG","File upload is successful!" ");Jsonout. Put("Info", FilePath);Response. setContentType("Text/html;charset=utf-8");Response. Getwriter(). Print(Jsonout. toString());}else{Logger. Info("File upload failed");Jsonout. Put("MSG","file format is incorrect, upload failed!" ");Response. setContentType("Text/html;charset=utf-8");Response. Getwriter(). Print(Jsonout. toString());}}}} private static String ReadFile (InputStreaminch) throws ioexception{String number ="";InputStreamReader reader = new InputStreamReader (inch);BufferedReader buffer = new BufferedReader (reader);String TMP = NULL;while ((tmp = buffer. ReadLine()) = null) {number + = tmp. ReplaceAll(" ","");} return number;} private static Boolean isValid (String str) {string regex ="^[a-z0-9a-z]+$";Return str. Matches(regex);}}
Get the upload file location configuration

Upload file Function-1

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.