springboot文件的上傳與下載


【轉載】http://blog.csdn.net/coding13/article/details/54577076

一下代碼為自己改進的代碼

1、工程結構圖

2、pom.xml文件依賴項


4.0.0

<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>demo</name>
<description>Demo project for Spring Boot</description>

<parent>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-parent</artifactId>
	<version>1.5.9.RELEASE</version>
	<relativePath/> <!-- lookup parent from repository -->
</parent>

<properties>
	<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
	<java.version>1.8</java.version>
</properties>

<dependencies>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-web</artifactId>
	</dependency>

	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-test</artifactId>
		<scope>test</scope>
	</dependency>
	
	   <dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-devtools</artifactId>
  <optional>true</optional>
</dependency>
</dependencies>

<build>
	<plugins>
		<plugin>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-maven-plugin</artifactId>
		</plugin>
	</plugins>
</build>

3、Application.java

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {

public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
}

}

4、FileController.java

package com.example.demo;

import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import ch.qos.logback.core.net.SyslogConstants;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;

@Controller
public class FileController {
@RequestMapping("/greeting")
public String greeting(@RequestParam(value="name", required=false, defaultValue="feng") String name, Model model) {
model.addAttribute("name", name);
return "greeting";
}
private static final Logger logger = LoggerFactory.getLogger(FileController.class);
//文件上傳相關代碼
@RequestMapping(value = "upload")
@ResponseBody
public String upload(@RequestParam("test") MultipartFile file) {
if (file.isEmpty()) {
return "文件為空";
}
// 獲取文件名
String fileName = file.getOriginalFilename();
logger.info("上傳的文件名為:" + fileName);
// 獲取文件的后綴名
String suffixName = fileName.substring(fileName.lastIndexOf("."));
logger.info("上傳的后綴名為:" + suffixName);
// 文件上傳后的路徑
String filePath = "E://test//";//服務器路徑
// 解決中文問題,liunx下中文路徑,圖片顯示問題
// fileName = UUID.randomUUID() + suffixName;
File dest = new File(filePath + fileName);
// 檢測是否存在目錄
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
try {
file.transferTo(dest);
return "上傳成功";
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "上傳失敗";
}

//文件下載相關代碼
@RequestMapping("/download")
@ResponseBody
public String downloadFile(HttpServletRequest request, HttpServletResponse response){
    String fileName = "index.html";

// String fileName = request.getParameter("name");
if (fileName != null) {
//當前是從該工程的WEB-INF//File//下獲取文件(該目錄可以在下面一行代碼配置)然后下載到C:\users\downloads即本機的默認下載的目錄
// String realPath = request.getServletContext().getRealPath( "\download\");
//絕對路徑可行,不知道上一行的相對路徑怎么設置。
String realPath = "D:\SpringToolWorkspace\demo\src\main\resources\download";
File file = new File(realPath, fileName);
if (file.exists()) {
response.setContentType("application/force-download");// 設置強制下載不打開
response.addHeader("Content-Disposition",
"attachment;fileName=" + fileName);// 設置文件名
byte[] buffer = new byte[1024];
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
// OutputStream os = response.getOutputStream();
String pathname = "e://download//filetest//"; //下載到自己設置的對應路徑,默認是瀏覽器下載的路徑

                File FilePath = new File(pathname);
                FilePath.mkdirs();
                File file2 = new File(FilePath,"file7.txt");
                
                file2.createNewFile();
                OutputStream os = new FileOutputStream(file2);
                
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer, 0, i);
                    
                    i = bis.read(buffer);
                }
                
                System.out.println("success");
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return "下載成功";
        }
      
    }
    return "文件不存在";
}

/* //文件下載相關代碼
@RequestMapping("/download")
public ResponseEntity<Byte[]> download(@RequestParam("name") String name) throws IOException{
String path =
return null;

}*/
//多文件上傳
@RequestMapping(value = "/batch/upload", method = RequestMethod.POST)
@ResponseBody
public String handleFileUpload(HttpServletRequest request) {
    List<MultipartFile> files = ((MultipartHttpServletRequest) request)
            .getFiles("file");
    MultipartFile file = null;
    BufferedOutputStream stream = null;
    for (int i = 0; i < files.size(); ++i) {
        file = files.get(i);
        if (!file.isEmpty()) {
            try {
                byte[] bytes = file.getBytes();
                File filePath2 = new File("e:"+File.separator+"test");   //上傳到指定目錄,若不指定默認上傳到工程的根目錄
                filePath2.mkdirs();
                File fileoutPutStream= new File(filePath2,file.getOriginalFilename());
                stream = new BufferedOutputStream(new FileOutputStream(
                        fileoutPutStream));
                stream.write(bytes);
                stream.close();

            } catch (Exception e) {
                stream = null;
                return "You failed to upload " + i + " => "
                        + e.getMessage();
            }
        } else {
            return "You failed to upload " + i
                    + " because the file was empty.";
        }
    }
    return "upload successful";
}

}

5、index.html

Getting Started: Serving Web Content

Get your greeting here

文件:
下載test

多文件上傳

文件1:

文件2:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM