Java implementation file upload and download

Source: Internet
Author: User
Tags save file

Write in front

"File Upload and download" is a lot of system features, such as PM\OA\ERP, etc., the common development mode of the system has B/s and C/s, while the former is mainly through the browser to access the Web server, generally using the seven layer Protocol "application layer HTTP" for data transmission, The latter mainly through the programming language development of the app as a client to access the server, generally using the seven layer Protocol "Transport layer TCP" for data transmission.
The article mainly completes the simple Java Web involves the file upload and the download function.

Body

1. Java Native servlet implementations:

    • Pom.xml configuration:
<dependency>      <groupId>javax</groupId>      <artifactId>javaee-api</artifactId>      <version>8.0</version>      <scope>provided</scope></dependency><dependency>      <groupId>javax</groupId>      <artifactId>javaee-web-api</artifactId>      <version>8.0</version>      <scope>provided</scope></dependency><dependency>      <groupId>javax.servlet</groupId>      <artifactId>jstl</artifactId>      <version>1.</version>      <scope>runtime</scope></dependency>
    • Web. XML configuration:
<welcome-file-list>      <welcome-file>/WEB-INF/view/jsp/upload/upload.jsp</welcome-file></welcome-file-list><!-- 声明Servlet对象 --><servlet>    <!-- 指定Servlet对象的名称 -->    <servlet-name>UploadServlet</servlet-name>    <!-- 指定Servlet对象的完整位置,包含包名和类名 -->    <servlet-class>pers.chaffee.servlet.UploadServlet</servlet-class></servlet><!-- 映射Servlet --><servlet-mapping>    <!--<servlet-name>与上面<Servlet>标签的<servlet-name>元素相对应,不可以随便起名  -->    <servlet-name>UploadServlet</servlet-name>    <!-- 用于映射访问URL -->    <url-pattern>/UploadFileServlet</url-pattern></servlet-mapping>
    • Servlet implementations:
@WebServlet ("/uploadservlet") public class Uploadservlet extends HttpServlet {@Override protected void doget (Httpser Vletrequest req, HttpServletResponse resp) {//Set file MIME type according to file extension Resp.setcontenttype (Getservletcontext (). Get        MimeType ("Hello.txt"));        Set download message response, prompt file Save attachment resp.setheader ("Content-disposition", "attachment;filename=" + "Hello"); /* * Set buffer * Is.read (b) Return when the file is read-1 */try {//input stream is project file, output stream points to browser InputS            Tream is = new FileInputStream ("E:\\hello.txt");            Provides a stream that writes binary data to the response servletoutputstream OS = Resp.getoutputstream ();            int len =-1;            Byte[] B = new byte[1024];            while (len = Is.read (b))! =-1) {os.write (b, 0, Len);            }//Close stream is.close ();        Os.close ();        } catch (FileNotFoundException e) {e.printstacktrace (); } catch (IOException e) {e.printstAcktrace ();        }} @Override protected void DoPost (HttpServletRequest req, HttpServletResponse resp) {//file uploaded to Local Disk factory class        Diskfileitemfactory factory = new Diskfileitemfactory ();        Sets the size of the memory buffer Factory.setsizethreshold (20480);        Set temporary file directory for temporary storage of factory.setrepository ("f:\\f") when uploading files are too large;        File Upload operation Core class servletfileupload upload = new Servletfileupload (factory);        Setting limits the size of a single upload file Upload.setfilesizemax (50480);        Set limit total upload file size Upload.setsizemax (80480);            This path is relative to the currently applied directory try {list<fileitem> formitems = upload.parserequest (req); if (formitems! = null && formitems.size () > 0) {//Diego represents single data for (Fileitem item:f Ormitems) {//handle fields that are not in the form if (!item.isformfield ()) {File sto                        refile = new File ("F:\\fromweb_" + item.getname ());           Save file to Hard disk             Item.write (StoreFile);        }}}} catch (Fileuploadexception e) {e.printstacktrace ();        } catch (Exception e) {e.printstacktrace (); }    }}
    • UPLOAD.JSP:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>

2. Java Web mainstream framework "SSM" implementation:

    • Pom.xml Configuration
<dependency> <groupId>org.springframework</groupId> <artifactid>spring-core</ Artifactid> <version>${spring.version}</version></dependency><dependency> <groupid >org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${ Spring.version}</version></dependency><dependency> <groupid>org.springframework</ Groupid> <artifactId>spring-web</artifactId> <version>${spring.version}</version>< /dependency><dependency> <groupId>org.springframework</groupId> <artifactId> Spring-context</artifactid> <version>${spring.version}</version></dependency>< Dependency> <groupId>org.springframework</groupId> <artifactid>spring-context-support</ Artifactid> <version>${spring.version}</version></dependency><dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <v Ersion>${spring.version}</version></dependency><dependency> <groupId> Org.springframework</groupid> <artifactId>spring-aspects</artifactId> <version>${ Spring.version}</version></dependency>
    • web. XML Configuration
<context-param> <param-name>contextConfigLocation</param-name> <!--<param-value> Classpath*:applicationcontext-*.xml</param-value>--> <param-value>classpath*:*. xml</ Param-value></context-param><listener> <listener-class>    Org.springframework.web.context.contextloaderlistener</listener-class></listener><listener> <listener-class>org.springframework.web.util.introspectorcleanuplistener</listener-class></ Listener><servlet> <servlet-name>dispatcherServlet</servlet-name> <servlet-class> Org.springframework.web.servlet.dispatcherservlet</servlet-class> <init-param> <param-name>con Textconfiglocation</param-name> <param-value>classpath:spring-mvc.xml</param-value> </init- Param> <load-on-startup>1</load-on-startup></servlet><servlet-mapping> < Servlet-name>diSpatcherservlet</servlet-name> <url-pattern>/service/*</url-pattern></servlet-mapping> 
    • spring-mvc.xml:
<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "Http://www.springframework.org/schema/beans" xmlns:p= "http://www.springframework.org/schema/p" xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:context= "Http://www.springframework.org/schema/context" xmlns:mvc= "Http://www.springframework.org/schema/mvc" Xsi:sche malocation= "Http://www.springframework.org/schema/beans Http://www.springframework.org/schema/beans/sprin G-beans-3.2.xsd Http://www.springframework.org/schema/context Http://www.springframework.org/schema/cont Ext/spring-context-3.2.xsd Http://www.springframework.org/schema/mvc Http://www.springframework.org/sche Ma/mvc/spring-mvc-3.2.xsd "> <!--start springmvc annotation Function-<mvc:annotation-driven/> <!--scan Controlle R (Controller layer injection)--<context:component-scan base-package= "Pers.chaffee.controller"/> <!--add a prefix to the model view-- > <bean id= "viewrEsolver "class=" Org.springframework.web.servlet.view.InternalResourceViewResolver "p:prefix="/web-inf/vi ew/jsp/"p:suffix=". jsp "/> <!--static resources do not walk controller--<mvc:resources mapping="/resources/** "location="/R   Esources/"/></beans>
    • servlet implementation:
    @RequestMapping (value = "/upload2", method = Requestmethod.post, consumes = {"Multipart/form-data"}) public Modelan DView Postupload (httpservletrequest request, httpservletresponse response) {//File upload core class Commonsmultip                Artresolver multipartresolver = new Commonsmultipartresolver (Request.getsession (). Getservletcontext ()); Determine if the request has a file upload if (Multipartresolver.ismultipart (Request)) {//Multiparthttpservletrequest resolution in the upload request            File Multiparthttpservletrequest multirequest = (multiparthttpservletrequest) request;            Get all the files in the upload request iterator<string> iter = Multirequest.getfilenames (); while (Iter.hasnext ()) {//Convert to spring supported file type Multipartfile Multipartfile = multirequest.g                Etfile (Iter.next ());                    if (file = null) {File LocalFile = new file ("f:\\f\\" + file.getoriginalfilename ());                        try {Writes the uploaded file to the specified location, here is the local folder File.transferto (LocalFile);                    } catch (IllegalStateException e) {e.printstacktrace ();                    } catch (IOException e) {e.printstacktrace ();        }}}} Modelandview Modelandview = new Modelandview ();        Modelandview.setviewname ("Upload/upload2");        return modelandview; } @RequestMapping (value = "/download", method = requestmethod.get) public responseentity<byte[]> Download (        ) throws IOException {byte[] responsebody;        Get file filename = new file ("E:\\hello.txt");        InputStream is = new FileInputStream (file);        Responsebody = new byte[is.available ()];        Is.read (responsebody);                Httpheaders headers = new Httpheaders ();            Set File type Headers.add ("Content-disposition", "attachment;filename=" + file.getname ());    Set HTTP status code httpstatus statecode = Httpstatus.ok;        return Data responseentity<byte[]> entity = new Responseentity<> (responsebody, headers, statecode);    return entity; }

Summary

Up to now, only preliminary completion of B/s upload and download, and file storage method only local disk. And the file transfer of C/S mode can consider thrift framework, thrift is a cross-platform cross-language RPC framework, using the process found that the data is not very large thrift application is a more appropriate C/s solution; In addition, File storage method can be selected according to the specific situation file server, database and so on.

Java implementation file upload and download

Related Article

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.