Java web Image Upload and file upload, java web Image Upload
Image Upload and file upload are essentially the same, and the image itself is also a file. File Upload is to upload images to the server. Although there are many ways, the underlying implementation is file read/write operations.
Notes
1. The form must write the attribute enctype = "multipart/form-data"
2. To ensure that the file can be uploaded successfully, the name attribute value of the file control must be consistent with the variable name of the control layer you submitted,
For example, if the space name is file, you need to define it in the background.
Private File file; // file control name
Private String fileContentType; // image type
Private String fileFileName; // file name
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. Controller to be submitted for page data
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; // file control name private String fileContentType; // Image type private String fileFileName; // File name 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 path of the image to be uploaded to the Server String names [] = fileFileName. split ("\\. "); String fileName =" "; if (names. length> = 1) {fileName = getRandomString (20) + ". "+ names [names. length-1];} String picPath = "upload/" + fileName; // path to save the image to the database File file1 = new File (root); try {FileUtils. copyFile (file, new File (file1, fileName) ;}} catch (IOException e) {e. printStackTrace ();} return SUCCESS;}/* obtain a random String */public String getRandomString (int length) {// length indicates the length of the generated String base = "abcdefghijklmnopqrstuvwxyz0123456789 "; 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 done by copying the file, and there are other methods
Method 2
@ Controller ("contractAction") public class ContractAction extends ActionSupport {private final static String UPLOADDIR = "/files"; // File Upload path. Create a private file under webContent; // The input control name is set to file // The collection of uploaded file names private String fileFileName; // The collection of uploaded file content types private String fileContentType; private String filename; public String upload () throws FileNotFoundException, IOException {String path = uploadFile (); // Save the database file Return SUCCESS;} // execute the upload function @ SuppressWarnings ("deprecation") public String uploadFile () throws FileNotFoundException, IOException {try {InputStream in = new FileInputStream (file ); string dir = ServletActionContext. getRequest (). getRealPath (UPLOADDIR); File fileLocation = new File (dir); // You can also manually create the target upload directory in the application root directory if (! FileLocation. exists () {boolean isCreated = fileLocation. mkdir (); if (! IsCreated) {// The creation of the target upload directory fails. You can perform other operations, such as throwing a custom exception. Return null;} // this. setFileFileName (getRandomString (20); String [] Name = this. getFileFileName (). split ("\\. "); 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 = "Random"; random Random = new Random (); StringBuffer sb = new StringBuffer (); for (int I = 0; I <length; I ++) {int number = random. nextInt (62); sb. append (str. charAt (number);} return sb. toString ();}}
In addition to single-Image Upload, multiple images are uploaded in the same principle.
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.ActionSup Port;/*** Multifile upload */public class FilesUploadAction extends ActionSupport {// upload File Storage path private final static String UPLOADDIR = "/upload "; // private List of uploaded files <File> file; // private List of uploaded File names <String> fileFileName; // private List of uploaded file content types <String> fileContentType; public List <File> getFile () {return file;} public void setFile (List <File> file) {this. file = file;} public List <String> getFileFil EName () {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 = fileContentType;} public String uploadform () throws Exception {HttpServletRequest request = ServletActionContext. getR Equest (); String webpath = null; // upload path for (int I = 0; I <file. size (); I ++) {// upload each file in a loop uploadFile (I); webpath = "upload/" + this. getFileFileName (). get (I) ;}return "SUCCESS" ;}// run the upload function private String uploadFile (int I) throws FileNotFoundException, IOException {try {InputStream in = new FileInputStream (file. get (I); String dir = ServletActionContext. getRequest (). getRealPath (UPLOADDIR); File fileLoc Ation = new File (dir); // You can also manually create the target upload directory in the application root directory if (! FileLocation. exists () {boolean isCreated = fileLocation. mkdir (); if (! IsCreated) {// The creation of the target upload directory fails. You can perform other operations, such as throwing a custom exception. 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 ;}}}