jsp開發之文件上傳

步驟

1、寫一個頁面(和前面文件下載的頁面寫在一起jsp文件下載

<%@ 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">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>
</head>
<body>
<a href="download?fileName=a.txt">下載</a>
<form action="upload" enctype="multipart/form-data" method="post">
    姓名:<input type="text" name="name"/><br/>
    文件:<input type="file" name="file"/><br/>
    <input type="submit" value="提交"/>
</form>
</body>
</html>

2、配置web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
	http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
  <!-- 配置前端控制器 -->

<!-- 配置前端控制器 -->
<servlet>
  <servlet-name>jqk</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
      <init-param>
         <param-name>contextConfigLocation</param-name>
         <param-value>classpath:applictionContext.xml</param-value>
      </init-param>
  <load-on-startup>1</load-on-startup>
</servlet>
     <servlet-mapping>
            <servlet-name>jqk</servlet-name>
             <url-pattern>/</url-pattern>
     </servlet-mapping>



</web-app>

3、導入jar包。由於我用的是springmvc。利用maven注入

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.nfha.wyz</groupId>
<artifactId>wyz</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>

<name>wyz Maven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>

<properties>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  <maven.compiler.source>1.7</maven.compiler.source>
  <maven.compiler.target>1.7</maven.compiler.target>
</properties>

<dependencies>
  <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.11</version>
    <scope>test</scope>
  </dependency>
  <!--文件下載包-->
  <dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.6</version>
  </dependency>
  <!--spring-->
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-core</artifactId>
    <version>4.1.7.RELEASE</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-beans</artifactId>
    <version>4.1.7.RELEASE</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-tx</artifactId>
    <version>4.1.7.RELEASE</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>4.1.7.RELEASE</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context-support</artifactId>
    <version>4.1.7.RELEASE</version>
  </dependency>

  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>4.1.7.RELEASE</version>
  </dependency>

  <dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.1</version>
  </dependency>

  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>4.1.7.RELEASE</version>
  </dependency>
</dependencies>

<build>
  <finalName>wyz</finalName>
  <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
    <plugins>
      <plugin>
        <artifactId>maven-clean-plugin</artifactId>
        <version>3.1.0</version>
      </plugin>
      <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
      <plugin>
        <artifactId>maven-resources-plugin</artifactId>
        <version>3.0.2</version>
      </plugin>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.8.0</version>
      </plugin>
      <plugin>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>2.22.1</version>
      </plugin>
      <plugin>
        <artifactId>maven-war-plugin</artifactId>
        <version>3.2.2</version>
      </plugin>
      <plugin>
        <artifactId>maven-install-plugin</artifactId>
        <version>2.5.2</version>
      </plugin>
      <plugin>
        <artifactId>maven-deploy-plugin</artifactId>
        <version>2.8.2</version>
      </plugin>
    </plugins>
  </pluginManagement>
</build>
</project>

4、配置applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <!--掃描註解-->
    <context:component-scan base-package="com.nfha.controller"></context:component-scan>
    <!--註解驅動-->
    <mvc:annotation-driven></mvc:annotation-driven>
    <!--靜態資源-->
    <mvc:resources location="/files/" mapping="/files/**"></mvc:resources>
    <!-- MultipartResovler解析器 -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="10000000"></property>
    </bean>
</beans>

5、寫controller

package com.nfha.controller;

import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.UUID;

@Controller
public class DemoController {
    @RequestMapping("download")
    public void downlode(String fileName, HttpServletResponse res, HttpServletRequest req)throws IOException {
        System.out.print("進入後臺");
        //設置響應流中文件進行下載
        res.setHeader("Content-Disposition", "attachment;filename="+fileName);
        //把二進制流放入到響應體中.
        ServletOutputStream out=res.getOutputStream();
        String path = req.getServletContext().getRealPath("files");
        System.out.println(path);
        File file = new File(path, fileName);
        byte []bytes= FileUtils.readFileToByteArray(file);
        out.write(bytes);
        out.flush();
        out.close();
    }
    @RequestMapping("upload")
    public String upload(MultipartFile file, String name) throws IOException{
        String fileName = file.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        //判斷上傳文件類型
        if(suffix.equalsIgnoreCase(".png")||0==0){
            String uuid = UUID.randomUUID().toString();
            System.out.print("值爲:"+uuid);
            FileUtils.copyInputStreamToFile(file.getInputStream(), new File("d:/"+uuid+suffix));
            return "/index.jsp";
        }else{
            return "error.jsp";
        }
    }
}

ok 結束了。此項目包含了文件下載和上傳。

來看看上傳完成的截圖吧。

over,有什麼不懂可以email我:[email protected]

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章