Java Web image upload and File Upload example detailed _java

Source: Internet
Author: User
Tags file upload mkdir java web stringbuffer

Java Web image upload and file upload

Picture uploads and file uploads are essentially the same, and the picture itself is a file. File upload is the picture uploaded to the server, although there are many ways, but the bottom of the implementation of the file is read and write operations.

Attention matters

1.form form Be sure to write properties enctype= "Multipart/form-data"

2. In order to ensure that the file can be uploaded successfully the Name property value of the file control is consistent with the control layer variable name that you submitted.

For example, the space name is file then you have to define it in the background

private file file; File Control Name

Private String filecontenttype;//Picture type

Private String Filefilename; Filename

1.jsp page

<%@ 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" > 
 
 

1. Page data needs to be submitted controller



Package com.cpsec.tang.chemical.action;
Import Java.io.File;
Import java.io.IOException;

Import Java.util.Random;
Import Javax.annotation.Resource;

Import Javax.servlet.http.HttpServletRequest;
Import Org.apache.commons.io.FileUtils;
Import Org.apache.struts2.ServletActionContext;

Import Org.springframework.stereotype.Controller;
Import Com.cpsec.tang.chemical.biz.LunboBiz;
Import Com.cpsec.tang.chemical.entity.Image;


Import Com.opensymphony.xwork2.ActionSupport; @Controller ("Lunboaction") public class Lunboaction extends Actionsupport {/** * */private static final long
  Serialversionuid = 1L;
  @Resource (name= "lunbobiz") private lunbobiz lunbobiz;
  private image Image; private file file; The file control name private string filecontenttype;//picture type private string filefilename;
  
  filename private Integer number;
    Public String Findimage () {image=lunbobiz.findimage ();
  return SUCCESS;
    Public String Alterimage () {image=lunbobiz.findimage (); Return SUCCESS;
    Public String AlterImage1 () {HttpServletRequest request = Servletactioncontext.getrequest ();
    String root = Request.getrealpath ("/upload");//the server path string Names[]=filefilename.split ("\.") to which the picture is to be uploaded;
    String filename= ""; if (names.length>=1) {filename=getrandomstring (20) + "."
    +NAMES[NAMES.LENGTH-1];
    The String picpath= "upload/" +filename;//picture is saved to the database path file File1=new file (root);
      try {fileutils.copyfile (file, new file (File1,filename));
    } catch (IOException e) {e.printstacktrace ();
  return SUCCESS; /* Get a random String */public string getrandomstring (int length) {//length represents the length of the build string base = "Abcdefghijklmnop   
    qrstuvwxyz0123456789 ";   
    Random Random = new Random ();   
    StringBuffer sb = new StringBuffer ();   
      for (int i = 0; i < length; i++) {int number = Random.nextint (Base.length ());   
    Sb.append (Base.charat (number));   
   return sb.tostring ();}  

}

 

This is the way to upload files by copying, and there are other ways

Method Two



@Controller ("Contractaction") public class Contractaction extends Actionsupport {private final static String Uplo Addir = "/files";//File upload path, create private file file under WebContent;  
  The input control name must be a file//upload file name collection private String filefilename; 
  
  Upload file content Type collection private String filecontenttype;
 
  private String filename; public string upload () throws FileNotFoundException, ioexception{string Path=uploadfile ();//File Save the path to the database return
  SUCCESS; ///Perform upload function @SuppressWarnings ("deprecation") public String UploadFile () throws FileNotFoundException, Ioexceptio  
      n {try {inputstream in = new FileInputStream (file); 
      String dir = servletactioncontext.getrequest (). Getrealpath (Uploaddir); 
      File Filelocation = new file (dir); 
        It is also possible to manually set up a target upload directory if (!filelocation.exists ()) {Boolean iscreated = Filelocation.mkdir () in the application root directory. 
          if (!iscreated) {///target upload directory creation fails, other processing can be done, such as throwing custom exceptions, which should not normally occur. Return Null
      }//This.setfilefilename (Getrandomstring (20));
      String[] Name=this.getfilefilename (). Split ("\ n."); String filename=getrandomstring (20) + "."
      +NAME[NAME.LENGTH-1];
      This.setfilefilename (FileName);
      System.out.println (FileName);
      File UploadFile = new file (dir, fileName);  
      OutputStream out = new FileOutputStream (uploadfile);  
      byte[] buffer = new byte[1024 * 1024];  
      int length;  
      while (length = in.read (buffer) > 0) {out.write (buffer, 0, length);  
      } in.close ();  
      Out.close ();
      return uploaddir.substring (1) + "\" +filefilename;  
      catch (FileNotFoundException ex) {return null;  
    catch (IOException ex) {return null; } public static String getrandomstring (int length) {String str= "abcdefghijklmnopqrstuvwxyzabcdefghijklmn
    OPQRSTUVWXYZ0123456789 ";
    Random random=new Random ();
    StringBuffer sb=new StringBuffer (); Forint i=0;i<length;i++) {int number=random.nextint (62);
    Sb.append (Str.charat (number));
  return sb.tostring ();

 }  

}

In addition to the single map upload and upload multiple pictures, the principle is the same

Package com.cpsec.tang.chemical.action; 
Import Java.io.File; 
Import Java.io.FileInputStream; 
Import java.io.FileNotFoundException; 
Import Java.io.FileOutputStream; 
Import java.io.IOException; 
Import Java.io.InputStream;
Import Java.io.OutputStream;
Import java.util.List;
Import Javax.servlet.http.HttpServletRequest;
Import Org.apache.struts2.ServletActionContext;


Import Com.opensymphony.xwork2.ActionSupport;  /** * Multiple File Upload/public class Filesuploadaction extends Actionsupport {//upload file Store path private final static String  
     Uploaddir = "/upload";  
     Upload file collection private list<file> file;  
     Upload file name collection private list<string> filefilename;  
     
     Upload file content Type collection private list<string> filecontenttype;  
     Public list<file> GetFile () {return File;  
     public void Setfile (list<file> file) {this.file = file; Public list<string> Getfilefilename () {return filEfilename;  
     public void Setfilefilename (list<string> filefilename) {this.filefilename = Filefilename;  
     Public list<string> Getfilecontenttype () {return filecontenttype; } public void Setfilecontenttype (list<string> filecontenttype) {this.filecontenttype = Fileconten  
     Ttype; Public String Uploadform () throws Exception {HttpServletRequest request = Servletactioncontext.ge
       Trequest (); String webpath=null;//upload path for (int i = 0; i < file.size (); i++) {//loop upload each file UploadFile (i 
         );
       Webpath= "upload/" +this.getfilefilename (). get (i);
     Return to "SUCCESS"; ///Perform upload function private String uploadfile (int i) throws FileNotFoundException, IOException {TR  
         y {inputstream in = new FileInputStream (File.get (i)); String dir = servletactioncontext.getrequest (). GetRealpath (Uploaddir); 
         File Filelocation = new file (dir); 
           It is also possible to manually set up a target upload directory if (!filelocation.exists ()) {Boolean iscreated = Filelocation.mkdir () in the application root directory. 
             if (!iscreated) {///target upload directory creation fails, other processing can be done, such as throwing custom exceptions, which should not normally occur. 
           return null; 
         } String Filename=this.getfilefilename (). get (i);
         File UploadFile = new file (dir, fileName);  
         OutputStream out = new FileOutputStream (uploadfile);  
         byte[] buffer = new byte[1024 * 1024];  
         int length;  
         while (length = in.read (buffer) > 0) {out.write (buffer, 0, length);  
         } in.close ();  
         Out.close ();
       return uploadfile.tostring ();  
       catch (FileNotFoundException ex) {return null;  
       catch (IOException ex) {return null;

 }  
     }
   }

Thank you for reading, I hope to help you, thank you for your support for this site!

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.