One : Introduce the necessary packages

 <!-- Upload files -->
<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>

Two : stay spring-service Middle configuration

<!-- Support to upload files -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8"></property>
<property name="maxUploadSize" value="10485760000"></property>
<property name="maxInMemorySize" value="40960"></property>
</bean>

3、 ... and : Upload files

3.1 Implementation method

 /**
* Upload files
* @param file
* @param request
* @return
*/
public JSONObject uploadFile(MultipartFile file, HttpServletRequest request){
// Get the file name
String fileName = file.getOriginalFilename();
// Get the file storage path
String path = request.getSession().getServletContext().getRealPath("").concat("/uploadFile");
// String path = getUploadPath(fileName,request);
// Upload files
File targetFile = new File(path, fileName);
if(!targetFile.exists()){
targetFile.mkdirs();
}
// preservation
try {
file.transferTo(targetFile);
} catch (Exception e) {
e.printStackTrace();
return resultErrorJson(fileName);
}
logger.info(fileName+" File upload succeeded ");
JSONObject jsonObject = new JSONObject();
jsonObject.put("key","true");
jsonObject.put("name",fileName);
jsonObject.put("path",path+"/"+fileName);
return jsonObject;
}

3.2 controller layer

 @RequestMapping(value="/upload")
@ResponseBody
public JSONObject upload(@RequestParam(value = "file") MultipartFile file, HttpServletRequest request){
fileOperation = new FileOperation();
// Return the file path after the file
return fileOperation.uploadFile(file,request);
}

3.3 When the text is submitted Pay attention to the submission format

 <form action="/file/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value=" Submit ">
</form>

Four : File download

/**
* Download the file
* @param fileName File template
* HttpServletRequest request,
* @param response response request
*/
public boolean download(String fileName, HttpServletRequest request,HttpServletResponse response) {
try {
response.setContentType("application/force-download");
response.setHeader("Content-Disposition", "attachment;fileName="
+ fileName);
String path = request.getSession().getServletContext().getRealPath("")+"/uploadFile/"+fileName;
File tempFile =new File(path); InputStream inputStream = new FileInputStream(tempFile);
OutputStream os = response.getOutputStream();
byte[] b = new byte[2048];
int length;
while ((length = inputStream.read(b)) > 0) {
os.write(b, 0, length);
}
os.flush();
os.close();
inputStream.close(); } catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println(" File download failed ");
return false;
}catch (IOException e) {
e.printStackTrace();
System.out.println(" File download failed ");
return false; }
return true;
}

5、 ... and Delete file

 /**
* Through the file absolute path Delete single file
* @param filePath
*/
public boolean delFile(String filePath) {
File delFile = new File(filePath);
if(delFile.isFile() && delFile.exists()) {
delFile.delete();
logger.info(" Delete file succeeded ");
return true;
}else {
logger.info(" There is no such document , Delete failed ");
return false;
}
}

SpringMVC Use in MultipartFile Upload, download and delete more related articles

  1. Share knowledge - Be happy with yourself :SpringMvc Single file upload and file download in

    Abstract :SpringMvc Single file upload and file download in :( Here is the core code ( You can use it directly ) You're welcome ) <!-- Set the file upload required jar--> <dependency> <grou ...

  2. Java Client operation FastDFS Achieve file upload download replace delete

    FastDFS Mr. Yu Qing, the author of this project, has developed it for us Java Corresponding SDK. There's a little bit of explanation here : Author Yu Qing did not update the latest Java SDK to Maven The central warehouse , At present, the latest version of the central warehouse is still 1.2 ...

  3. SpringMVC Integrate fastdfs-client-java Realization web File upload download

    original text :http://blog.csdn.net/wlwlwlwl015/article/details/52682153 This article blog Mainly record SpringMVC Integrate FastDFS Of Java Client real ...

  4. SpringMVC ajax Technology no refresh file upload download delete example

    Reference resources Spring MVC Upload file instance in SpringMVC combination ajaxfileupload.js Realization ajax No refresh file upload Spring MVC File upload download (FileOperateUtil.ja ...

  5. SpringMVC( 3、 ... and ) RESTful Architecture and file upload and download

    RESTful framework REST Full name :Representational State Transfer. State transformation of resource presentation layer . Is the most popular Internet software architecture . It has a clear structure . Meet the standard . Easy to understand . Easy to expand , the ...

  6. SpringMVC Use in CommonsMultipartResolver Upload files

    summary : CommonsMultipartResolver Is based on Apache Of Commons FileUpload To achieve the file upload function . So in the project, we need the corresponding jar file . FileUpload Version for 1 ...

  7. SpringMVC Learning notes 8 : File upload download ( turn )

    from :http://www.cnblogs.com/WJ-163/p/6269409.html One . Key steps ① The introduction of the core JAR file SpringMVC File upload , You need to add two more jar package . One is on the file ...

  8. java in io Stream file upload and download

    newly build io.jsp <%@ page language="java" contentType="text/html; charset=UTF-8" page ...

  9. JAVA Use in FTPClient Achieve file upload and download instance code

    One . Upload files The principle is not introduced , Let's look at the code directly ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 ...

Random recommendation

  1. First use and installation express

    install Nodejs Go to Nodejs The official website downloads and installs the corresponding installation package according to its own operating system . We have NodeJS and npm Environmental Science .npm yes Node Package management tools , Will be installed NodeJS It's installed at the same time . You can view the version with the following command ...

  2. plsql Connect to local database

    1.  download 64 position Oracle, Unzip two files , After decompression, merge the files , install : 2.  download PL/SQL, install : 3.  download instantclient-basic-win32-11.2.0.1.0.zip ...

  3. java Introduction to exception handling summary

    (1) Exceptions and errors abnormal (Exception): Abnormal events , It interrupts the program , Accidents in operation , The program itself can handle , Prevent program interruption : Exception information that will be captured in the program , And admonish programmers , It doesn't require the program to deal with it .catch ...

  4. Development “todolist“” The project and its own insights

    One , Project title :  Realization “todolist project ” This project can mainly practice js Manipulation dom event , The logical relationship between event triggers , And how to write to the cache , Access to the cache . Fix . Two ,todolist brief introduction ToDoList It's a very good one ...

  5. C#--- Packing 、 A case of unpacking

    using System; namespace ConsoleApplication1 { interface IInterface { void Add(int num); } struct Tes ...

  6. utilize ComponentWillReceiveProps Solve the asynchronous problem

    1. I met such a problem in my work : There are multiple buttons , Click different buttons to send different requests ( Transmitted id Different ) And display the pop-up window , The pop-up window shows the data sent back by the back end . But like clicking on the second button , The data in the pop-up window is still the data in the first pop-up window . 2. reason ...

  7. prequeue receive queue backlog queue

    prequeue and backlog and receive 5.6 TCP prequeue http://blog.csdn.net/u011130578/article/details/44814201 t ...

  8. ubuntu Web pages can't watch videos

    sudo apt-get install flashplugin-nonfree sudo apt-get install aptitude sudo aptitude install ubuntu- ...

  9. git Use of version control

    In particular : All the knowledge notes in this article are learning “ Show seriousness ” Classmate git The course records . Senior personal website address :http://biaoyansu.com Thank you ! One .git It's version control Two . Create a warehouse locally 1. Enter the new ...

  10. 【 The way of mass production 】 The way of mass SET Model

    This paper introduces set Model . One The scene of providing massive Services scene 1: How to make Huangcun computer room TWS Machine access to Huangcun machine room APP service , avoid TWS Cross machine room call Yongfeng machine room APP machine ? scene 2:DB and Redis How to realize the separation of fast and slow , ...