Java file upload and file download are relatively common functions in program development. The following article will introduce to you three solutions to implement file upload and download in Java. The specific details are as follows;
The first point: Java code implements file upload
FormFile file=manform.getFile(); String newfileName = null;String newpathname=null;String fileAddre="/numUp";try {InputStream stream = file.getInputStream();// Read the file into String filePath = request.getRealPath(fileAddre);//Fetch the current path of the system File file1 = new File(filePath);//Add the function of automatically creating directories ((File) file1).mkdir(); newfileName = System.currentTimeMillis()+ file.getFileName().substring(file.getFileName().lastIndexOf('.'));ByteArrayOutputStream baos = new ByteArrayOutputStream();OutputStream bos = new FileOutputStream(filePath + "/"+ newfileName);newpathname=filePath+"/"+newfileName;System.out.println(newpathname);// Create an output stream for uploading files System.out.println(filePath+"/"+file.getFileName());int bytesRead = 0;byte[] buffer = new byte[8192]; while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {bos.write(buffer, 0, bytesRead);// Write the file to the server}bos.close();stream.close();} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}The second point: implement file upload on the Jsp page
package com.vogoal.util;import java.io.BufferedOutputStream;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.text.SimpleDateFormat;import java.util.ArrayList;import java.util.Date;import java.util.Hashtable;import javax.servlet.ServletInputStream;import javax.servlet.http.HttpServletRequest;public class JspFileUpload {/** request object*/private HttpServletRequest request = null;/** Path to upload the file*/private String uploadPath = null;/** The size of bytes is obtained each time*/private static int BUFSIZE = 1024 * 8;/** Hashtable that stores parameters */private Hashtable paramHt = new Hasptable();/** ArrayList that stores the file name of the uploaded file */private ArrayList updFileArr = new ArrayList();/*** Set the request object. * * @param request* HttpServletRequest request object*/public void setRequest(HttpServletRequest request) {this.request = request;}/*** Set the file upload path. * * @param path* The upload path of the file specified by the user. */public void setUploadPath(String path) {this.uploadPath = path;}/*** The main program for file upload processing. ������B* * @return int Operation result 0 The file operation was successful; 1 request object does not exist. 2 The file saving path is not set or the file saving path is incorrect; 3* The correct enctype is not set; 4 The file operation is abnormal. */public int process() {int status = 0;// Before uploading the file, check the request object, upload path and enctype. status = preCheck();// Returns the error code when an error occurs. if (status != 0)return status;try {// �� parameter or file name �u��String name = null;// parameter valueString value = null;// Whether the read stream is the file flag bit boolean fileFlag = false;// file to be stored. File tmpFile = null;// The name of the uploaded file String fName = null;FileOutputStream baos = null;BufferedOutputStream bos = null;// ��HashtableparamHt = new Hashtable();updFileArr = new ArrayList();int rtnPos = 0;byte[] buffs = new byte[BUFSIZE * 8];// �Get ContentTypeString contentType = request.getContentType();int index = contentType.indexOf("boundary=");String boundary = "--" + contentType.substring(index + 9);String endBoundary = boundary + "--";// � Get the stream from the request object. ServletInputStream sis = request.getInputStream();// Read 1 line while ((rtnPos = sis.readLine(buffs, 0, buffs.length)) != -1) {String strBuff = new String(buffs, 0, rtnPos);// Read 1 line of data�n��if (strBuff.startsWith(boundary)) {if (name != null && name.trim().length() > 0) {if (fileFlag) {bos.flush();baos.close();bos.close();baos = null;bos = null;updFileArr.add(fName);} else {Object obj = paramHt.get(name);ArrayList al = new ArrayList();if (obj != null) {al = (ArrayList) obj;}al.add(value);System.out.println(value);paramHt.put(name, al);}}name = new String();value = new String();fileFlag = false;fName = new String();rtnPos = sis.readLine(buffs, 0, buffs.length);if (rtnPos != -1) {strBuff = new String(buffs, 0, rtnPos);if (strBuff.toLowerCase().startsWith("content-disposition: form-data; "))) {int nIndex = strBuff.toLowerCase().indexOf("name=/"");int nLastIndex = strBuff.toLowerCase().indexOf("/"", nIndex + 6);name = strBuff.substring(nIndex + 6, nLastIndex);}int fIndex = strBuff.toLowerCase().indexOf("filename=/"");if (fIndex != -1) {fileFlag = true;int fLastIndex = strBuff.toLowerCase().indexOf("/"", fIndex + 10);fName = strBuff.substring(fIndex + 10, fLastIndex);fName = getFileName(fName);if (fName == null || fName.trim().length() == 0) {fileFlag = false;sis.readLine(buffs, 0, buffs.length);sis.readLine(buffs, 0, buffs.length);sis.readLine(buffs, 0, buffs.length);continue;}else{fName = getFileNameByTime(fName);sis.readLine(buffs, 0, buffs.length);sis.readLine(buffs, 0, buffs.length);}}} else if (strBuff.startsWith(endBoundary)) {if (name != null && name.trim().length() > 0) {if (fileFlag) {bos.flush();baos.close();bos.close();baos = null;bos = null;updFileArr.add(fName);} else {Object obj = paramHt.get(name);ArrayList al = new ArrayList();if (obj != null) {al = (ArrayList) obj;}al.add(value);paramHt.put(name, al);}}} else {if (fileFlag) {if (baos == null && bos == null) {tmpFile = new File(uploadPath + fName);baos = new FileOutputStream(tmpFile);bos = new BufferedOutputStream(baos);}bos.write(buffs, 0, rtnPos);baos.flush();} else {System.out.println("test :" + value + "--" + strBuff);value = value + strBuff;}}}} catch (IOException e) {status = 4;}return status;}private int preCheck() {int errCode = 0;if ( request == null )return 1;if ( uploadPath == null || uploadPath.trim().length() == 0 )return 2;else{File tmpF = new File(uploadPath);if (!tmpF.exists())return 2;}String contentType = request.getContentType();if ( contentType.indexOf("multipart/form-data") == -1 )return 3;return errCode;}public String getParameter(String name){String value = "";if ( name == null || name.trim().length() == 0 )return value;value = (paramHt.get(name) == null)?"":(String)((ArrayList)paramHt.get(name)).get(0);return value;}public String[] getParameters(String name){if ( name == null || name.trim().length() == 0 )return null;if ( paramHt.get(name) == null )return null;ArrayList al = (ArrayList)paramHt.get(name);String[] strArr = new String[al.size()];for ( int i=0;i<al.size();i++ )strArr[i] = (String)al.get(i);return strArr;}public int getUpdFileSize(){return updFileArr.size();}public String[] getUpdFileNames(){String[] strArr = new String[updFileArr.size()];for ( int i=0;i<updFileArr.size();i++ )strArr[i] = (String)updFileArr.get(i);return strArr;}private String getFileName(String input){int fIndex = input.lastIndexOf("//");if (fIndex == -1) {fIndex = input.lastIndexOf("/");if (fIndex == -1) {return input;}} input = input.substring(fIndex + 1);return input;}private String getFileNameByTime(String input){int index = input.indexOf(".");Date dt = new Date();SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");return input.substring(0,index) + sdf.format(dt) + input.substring(index);}}2. Reference the Java class in the Jsp page:
<%@page import="com.vogoal.util.JspFileUpload"%><%//Initialize JspFileUpload jfu = new JspFileUpload();//Set the request object jfu.setRequest(request);//Set the uploaded file path jfu.setUploadPath("C://");//Upload processing int rtn = jfu.process();//Get the values of other input control parameters in form String username = jfu.getParameter("username");//If there are multiple input controls for the same parameter, return the array String[] usernameArr = jfu.getParameters("username");//Get the name of the uploaded file String[] fileArr = jfu.getUpdFileNames();//Get the number of uploaded files, this method is a bit useless int fileNumber = jfu.getUpdFileSize();//The following is the code output for the test. // out.println("parameter:" + username);// out.println("parameter size:" + usernameArr.length);// out.println("fileArr size:" + fileArr.length);// if (fileArr.length > 0)// out.println("fileArr 0:" + fileArr[0]);%>The third point: struts2 implements file upload and download
Step 1: Add commons-fileupload-1.2.1.jar and commons-io-1.3.2.jar under WEB-INF/lib. These two files can be downloaded from http://commons.apache.org/.
Step 2: Set the enctype of the form table to: "multipart/form-data", as follows:
Java code
public class UploadAction{ private File uploadImage; //File private String uploadImageContentType;//File type private String uploadImageFileName;//File name private String bookname;//Book name private String author;//Author private String savePath;//File save location//Attribute getter/setter method public String upload() throws Exception{ //Implement upload code, I/O operation completes return "uploadSuccess"; } }Note: The file domain in a form corresponds to three properties in the Action, namely, file name, and file type. The naming is fixed. The file name must be the same as the file domain name in the form (uploadImage). The file name is: File + FileName, and file type: File + ContentType.
Step 4: Configure our upload action into struts.xml.
Java code
<action name="upload"> <param name="savePath">/uploadFile</param> <result>/success.jsp</result> </action>
Note: To specify the save directory of the uploaded file on the server, you need to define the savePath variable in UploadAction and add the corresponding setter and getter methods to it, so that Struts2 can assign the /uploadFile value to the savePath attribute, that is, to use the savePath variable in UploadAction, you must define it in UploadAction.
Manual configuration file filtering type
<param name="allowTypes"> image/bmp,image/png,image/gif,image/jpeg </param>
Manual configuration file size limit
<param name="maximumSize" >1048576</param>
Use Struts2's file upload interceptor to implement file filtering
Struts2 provides a file upload interceptor - fileUpload. By configuring this interceptor, filtering of uploaded files can be easily achieved.
When configuring a fileUpload interceptor, you can specify two parameters for it:
allowedTypes: Specifies the file type that is allowed to be uploaded, separated by an English comma (,).
maximumSize: Specifies the file size allowed to be uploaded in bytes.
Tip: By configuring a fileUpload interceptor, you can easily implement file filtering. When the file filtering fails, the system will automatically transfer to the input logical view. Therefore, the logical view named input must be configured for the Action. In addition, the interceptor reference of defaultStack must be configured for the Action.
Use Struts2's interceptor to implement file filtering configuration as follows:
<action name="uploadFileAction"> <interceptor-ref name="defaultStack"> <!-- Configure the file type allowed to be uploaded, separated by multiple using ","--> <param name="fileUpload.allowedTypes"> image/bmp,image/png,image/gif,image/jpeg,image/jpg,image/x-png,image/pjpeg </param> <!-- Configure the file size allowed to be uploaded, unit bytes, this example is: 1MB --> <param name="fileUpload.maximumSize">1048576</param> </interceptor-ref> <result name="input">/jsp/oneFileFileupload.jsp</result> <result name="success">/jsp/result.jsp</result> </action>
When the user fails to upload, there is a certain prompt message. In Struts2, use the <s:fielderror/> tag to output the error message to the page.
Note: If you want to use Struts2 error prompt information, the Action class that uploads the file must inherit ActionSupport, otherwise Struts2 will not provide the output error prompt information function.
We can configure resource files (.properties) to save the information output to the user.
struts.messages.eror.file.too.large: When the upload file size exceeds the set value, Struts2 will output the prompt information corresponding to the key.
struts.messages.error.content.type.not.allowed: When the uploaded file type does not meet the set value, Struts2 will output the prompt information corresponding to the key.
struts.messages.error.uploading: When an unknown error occurs when uploading a file, Struts2 will output the prompt information corresponding to the key.
We also need to configure the resource file into the struts.xml file. Next, we have to view our resource file. It already contains Chinese. We have to convert it and then configure it into the project.
Set the resource file in struts.xml:
<constant name="struts.custom.i18n.resources" value="messages"/> or <constant name="struts.custom.i18n.resources" value="messages_zh_CN"/>
Use the command native2ascii d:/messages.properties d:/messages_zh_CN.properties to convert the original resource file into supported ones.
Note: Keep international, the name suffix of the resource file is: *_zh_CN + file extension.
The principle of uploading multiple files is the same as above, but it should be noted that the name attribute names of multiple file fields must be the same, and in Action, File [] or List<File> should be used to receive it.
I personally think that using this method to upload multiple files is not
very good.
Struts2 for file download
Struts2 provides a stream result type, which is specifically used to support file downloading. When specifying the stream result type, an inputName parameter needs to be configured, which specifies an input stream, which is the entrance to the downloaded file (that is, the file can be downloaded in a stream through this entry).
Implement the action of file download
public class FileDownloadAction implements Action{ //This property value is specified in the configuration file. Struts2 will automatically inject (i.e., assign a value). You need to provide the setter and getter methods private String inputPath;//Specify the complete path of the file to be downloaded (path name + file name) /* * The Action class that implements the download should provide a method to return an InputStream instance. The corresponding inputName property value in <result...//public InputStream getTargetFile() throws Exception{ return ServletActionContext.getServletContext().getResourceAsStream(inputPath); } //The execute method that handles user requests, which returns the success string public String execute() throws Exception{ return "success"; } }The corresponding Action configuration in struts.xml file
<action name="download"><!--Specify the location of the downloaded resource--><param name="inputPath">/uploadFile/demo.txt</param><!--Configure the result type as stream--><result name="success" type="stream"><!--Specify the file type of the downloaded file--><param name="contentType"></param><!--Specify the file location of the downloaded file--><param name="inputName">targetFile</param><!--Specify the download method of the downloaded file and the file name saved at the time of download. The file name when saving file must have an extension, and the extension indicates the icon of the download type--><param name="contentDisposition">attachment;filename=Struts2.txt</param><!--Specify the buffer size of the downloaded file--><param name="bufferSize">4096</param></result></action>
The above are the three solutions for implementing file upload and download in Java introduced to you by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support to Wulin.com website!