"Reprint" http://blog.csdn.net/coding13/article/details/54577076
Code for your own improved code.
1. Engineering structure diagram
2. pom.xml file dependencies
<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> <artif Actid>spring-boot-starter-web</artifactid> </dependency> <depeNdency> <groupId>org.springframework.boot</groupId> <artifactid>spring-boot-starter-tes t</artifactid> <scope>test</scope> </dependency> <dependency> <group Id>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& lt;/groupid> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </PL Ugins></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);
File Upload related code
@RequestMapping (value = "Upload")
@ResponseBody
Public String Upload (@RequestParam ("test") Multipartfile file) {
if (File.isempty ()) {
Return "file is empty";
}
Get file name
String fileName = File.getoriginalfilename ();
Logger.info ("uploaded file name:" + fileName);
Gets the suffix name of the file
String suffixname = filename.substring (Filename.lastindexof ("."));
Logger.info ("uploaded suffix named:" + Suffixname);
The path after file upload
String FilePath = "e://test//";//server path
Solve Chinese problem, liunx Chinese path, picture display problem
FileName = Uuid.randomuuid () + suffixname;
File Dest = new file (FilePath + fileName);
Detect if a directory exists
if (!dest.getparentfile (). exists ()) {
Dest.getparentfile (). Mkdirs ();
}
try {
File.transferto (dest);
Return "upload success";
} catch (IllegalStateException e) {
E.printstacktrace ();
} catch (IOException e) {
E.printstacktrace ();
}
Return "Upload failed";
}
//文件下载相关代码@RequestMapping("/download")@ResponseBodypublic String downloadFile(HttpServletRequest request, HttpServletResponse response){ String fileName = "index.html";
//String FileName = Request.getparameter ("name");
if (fileName! = null) {
//is currently getting the file from the project's web-inf//file//(the directory can be configured in the following line of code) and then downloaded to C:\users\downloads, the default downloaded directory for this machine
//String Realpath = Request.getservletcontext (). Getrealpath ("\download\"); The
//absolute path is feasible and does not know how to set the relative path of the previous line.
String Realpath = "D:\SpringToolWorkspace\demo\src\main\resources\download";
File File = new file (Realpath, fileName);
if (file.exists ()) {
Response.setcontenttype ("Application/force-download");//setting force download does not open
Response.AddHeader ("Content-disposition",
"attachment;filename=" + filename);//Set file name
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//";//download to the corresponding path of your own settings, default is the path of browser download
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 "Download succeeded"; }} Return "file does not exist";}
/*//File Download related code
@RequestMapping ("/download")
Public responseentity
}*///multiple File upload @requestmapping (value = "/batch/upload", method = Requestmethod.post) @ResponseBodypublic 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"); Upload to the specified directory, if you do not specify the default upload to the project's root directory 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 toUpload "+ i +" = "+ E.getmessage (); }} else {return ' failed to upload ' + i + "because the file was empty."; }} return "Upload successful";}
}
5, index.html
Get your greeting here
Download test
Multiple file uploads
Uploading and downloading of springboot files