Java batch upload and download large files

The first point: Java code to achieve file upload

FormFile file = manform.getFile();

String newfileName = null;

String newpathname = null;

String fileAddre = "/numUp";

try

{

    InputStream stream = file.getInputStream (); // read the file

    String filePath = request.getRealPath (fileAddre); // get current path systems

    File file1 = new File (filePath); // add a function to automatically create a directory

    ((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 upload file output stream

    System.out.println(filePath + "/" + file.getFileName());

    read byte int = 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: Upload Files on Jsp page

com.vogoal.util package;

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;

    / Upload file path ** * /

    private String uploadPath = null;

    / ** get each read byte size * /

    private static int BUFSIZE = 1024 * 8;

    / ** storage parameters Hashtable * /

    private Hashtable paramHt = new Hasptable();

    ArrayList file name of the file / ** * storage upload /

    private ArrayList updFileArr = new ArrayList();

    /**

     * Set request object.

     *

     * @param request

     *            HttpServletRequest request对象

     */

    public void setRequest(HttpServletRequest request) {

        this.request = request;

    }

    /**

     * Set file upload path.

     *

     * @Param path

     * Upload a user-specified file path.

     */

    public void setUploadPath(String path) {

        this.uploadPath = path;

    }

File upload handling procedures

    /**

     * Handling file uploads main program. B

     *

     * @Return int operating results document the successful operation 0; 1 request object does not exist. 2 is not set file path or file path is incorrect; 3

     * Not set the correct enctype; 4 abnormal file operation.

     */

    public int process() {

        int status = 0;

        // before the file upload, the object of the request, upload path and enctype be check.

        status = preCheck();

        // error when the error code is returned.

        if (status != 0)

            return status;

        try {

            // parameter or file name u

            String name = null;

            value // Parameters

            String value = null;

            // flag is flowing to read the file

            boolean fileFlag = false;

            // file to be stored.

            File tmpFile = null;

            // name of the uploaded file

            String fName = null;

            FileOutputStream baos = null;

            BufferedOutputStream bos = null;

            Hashtable // storage parameters

            paramHt = new Hashtable();

            updFileArr = new ArrayList();

            int rtnPos = 0;

            byte[] buffs = new byte[BUFSIZE * 8];

            // get ContentType

            String 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 one line

            while ((rtnPos = sis.readLine(buffs, 0, buffs.length)) != -1) {

                String strBuff = new String(buffs, 0, rtnPos);

                // 1 read data line 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();

                    File flag = 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) {

                                File flag = 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. Jsp pages referenced in the Java class:

<%@page import="com.vogoal.util.JspFileUpload"%>

<%

    //initialization

    JspFileUpload jfu = new JspFileUpload();

    // Set the request object

    jfu.setRequest(request);

    // set the upload file path

    jfu.setUploadPath("C:\\");

    // upload process

    int rtn = jfu.process();

    // get the value of other input control parameters in the form

    String username = jfu.getParameter("username");

    // If the same parameter corresponding to a plurality of input controls, returns an array

    String[] usernameArr = jfu.getParameters("username");

    // Get the name of the uploaded file

    String[] fileArr = jfu.getUpdFileNames();

    // get the number of upload files, this method is a little tasteless

    int fileNumber = jfu.getUpdFileSize();

// The following code is the test output.

//       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: upload and download files to achieve struts2

The first step: Add commons-fileupload-1.2.1.jar, commons- io-1.3.2.jar in the WEB-INF / lib. Both files from http://commons.apache.org/ download.

Step two: enctype form table is provided: "multipart / form-data", as follows:

Java code

public class UploadAction{ 

  private File uploadImage; //文件 

  private String uploadImageContentType; // type of file 

  private String uploadImageFileName; // file name 

  private String bookname; // Title 

  private String author; // Author 

  private String savePath; // location to save the file 

  getter // property / setter methods 

  public String upload() throws Exception{ 

  // to upload the code, I / O operation is complete 

  return "uploadSuccess"; 

  } 

}

 

Note: a form of files in the corresponding Action field in three properties, namely, file, file name, file type, naming is fixed, the file name must be in the form of domain names the same file (uploadImage), the file name: File + FileName, file type: file + ContentType.

 

Step 4: We upload the configuration to struts.xml in Action.

<action name="upload" class="com.gqy.UploadAction"> 

      <param name="savePath">/uploadFile</param> 

      <result>/success.jsp</result>  </action>

Note: Save directory on the server designated to upload files, you need to define savePath variables and add the appropriate setter and getter methods in UploadAction, the ease of the Struts2 / uploadFile savePath property value is assigned, that in order to use in UploadAction savePath variables must be defined in UploadAction.

Profile Filter Type:

<param name="allowTypes">       image/bmp,image/png,image/gif,image/jpeg   </param>

Manually configure the file size limit

<param name="maximumSize" >1048576</param> 

File upload using Struts2 interceptor implementation file filter

Struts2 provides a file upload interceptor -fileUpload, you can easily upload files to achieve filtering by configuring the interceptor.

When you configure fileUpload interceptor, you can assign two parameters:

§ allowedTypes: specify allowed to upload file types, comma (,) to separate multiple file types.

§ maximumSize: Specifies the allowed upload file size in bytes.

Tip: By configuring fileUpload interceptor, can easily achieve the paper filter, the filter when the file fails, the system automatically input into a logical view, it is necessary to configure the input for the named logical view of the Action, in addition, must be displayed defaultStack configured interceptor references for Action.

Implemented using Struts2 interceptor filter configuration file as follows:

 <action name="uploadFileAction" class="com.actions.UploadFileAction"> 

           <interceptor-ref name="defaultStack"> 

              <! - configuration allows upload file type, with a plurality of "," separated ->                  

              <param name="fileUpload.allowedTypes">                      

                    image/bmp,image/png,image/gif,image/jpeg,image/jpg  

                    ,image/x-png, image/pjpeg 

              </param>                 

              <! - configuration allows upload file size, in bytes, in this case: 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 users upload fails, you need to have some message. In Struts2 using <s: fielderror /> tag can be output to the error page.

Note: To use Struts2 Action class error information, upload files, you must inherit ActionSupport, otherwise Struts2 does not provide an error message output function.

We can configure the resource file (.properties) to save the output information to the user.

struts.messages.eror.file.too.large: When the upload file size exceeds the value set, Struts2 outputs the presentation information corresponding to the key.

struts.messages.error.content.type.not.allowed: When uploading a file type does not match the set value, Struts2 outputs the presentation information corresponding to the key.

struts.messages.error.uploading: When Unknown error when uploading files, Struts2 will prompt information of the corresponding key.

We will also file allocation of resources to struts.xml file, let's look at our resources file already contains Chinese, have to convert it to conduct some reallocation to the project.

Set in the resource file in struts.xml:

<constant name="struts.custom.i18n.resources" value="messages"/>或

<constant name="struts.custom.i18n.resources" value="messages_zh_CN"/>

Command native2ascii d: \ messages.properties d: \ messages_zh_CN.properties to convert existing resources to support the document.

Note: Keep internationalization, the resource file name suffix: * _zh_CN + file name extension form.

For the principle of multiple files to upload as above, but should be noted that, name the file attribute multiple domain name must be the same, and should be used in the Action File [] or List <File> to receive.

Personally I feel that such a multiple file upload is not very good.

Struts2 download files:

Struts2 provides a stream result type, the result type is designed to support file download function. When the result type specified stream, a need to configure inputName parameter that specifies an input stream, the input stream is downloaded file entry (i.e. flow inlet manner to achieve the download files).

Implementation file download Action

     public class FileDownloadAction implements Action{ 

          

            // the attribute value specified in the configuration file, Struts2 will automatically injection (i.e. assignment), it is necessary to provide for the property setter and getter methods 

            private String inputPath; // specify the full path of the file to be downloaded (pathname + file name) 

            /*

              * Implementation of the Action class should provide a return InputStream instance, the method corresponds to      

                 <Result ... /> in the attribute value targetFile inputName

            */

            public InputStream getTargetFile() throws Exception{ 

               return  ServletActionContext.getServletContext().getResourceAsStream(inputPath); 

            } 

            // execute method that user's request, the method returns a string success 

            public String execute() throws Exception{ 

               return "success"; 

            }

         @Override

         public void doIt (WSF arg0, arg1 Input) {

              // TODO Auto-generated method stub

             

         } 

         }

Action corresponding to the configuration file struts.xml

<action name="download" class="com.FileDownloadAction">

   <! - Specifies the location of the resource is downloaded ->

      <param name="inputPath">/uploadFile/demo.txt</param>

   <! - as a result of the configuration of stream type ->

   <result name="success" type="stream">

       <! - Specifies the type of file to download the file ->

          <param name="contentType"></param>

       <! - Specifies the download file location ->

          <param name="inputName">targetFile</param>

       <! - save the file name to download and download download the specified file, the file name when saving filename must have the extension, the extension indicates the type of download icon ->

          <param name="contentDisposition">

                attachment;filename=Struts2.txt

          </param>

       <! - Specifies the buffer size to download the file ->

          <param name="bufferSize">4096</param>

   </result>

</action>

Most of the back-end code logic is the same, currently supports MySQL, Oracle, SQL. Before using the need to configure the database, you can refer me to write this article: http://blog.ncmem.com/wordpress/2019/08/12/java-http%E5%A4%A7%E6%96%87 % E4% BB% B6% E6 % 96% AD% E7% 82% B9% E7% BB% AD% E4% BC% A0% E4% B8% 8A% E4% BC% A0 /

 

Guess you like

Origin www.cnblogs.com/songsu/p/12557501.html