Heim > Java > javaLernprogramm > Hauptteil

So erstellen Sie Springboot-Upload-Dateien

坏嘻嘻
Freigeben: 2018-09-14 16:22:26
Original
3667 Leute haben es durchsucht

Da ich mit der High-End-Front-End-Verarbeitung nicht vertraut bin, möchte ich Inhalte direkt über MVC übertragen. Daher habe ich die Thymeleaf-Vorlage ausgewählt, um das Problem der Übergabe von Werten an das Front-End zu lösen.

  1. application.properties-Datei

#访问超市时间的设置ribbon.
ConnectTimeout=60000ribbon.
ReadTimeout=60000
# 开启多文件上传
spring.servlet.multipart.
enabled=true 
spring.servlet.multipart.file-size-threshold =0
#单个文件大小
#spring.http.multipart.maxFileSize=10MB
#设置总上传的数据大小
#spring.http.multipart.maxRequestSize=10MB
#升级到2.0后需要改成
#单个文件大小spring.servlet.
multipart.max-file-size=10Mb 
#设置总上传的数据大小 
spring.servlet.multipart.
max-request-size=10Mb
#上传路径upload_path=D:/file_statics
#下载路径download_path=D:/file_statics
Nach dem Login kopieren

2.Controller-Code

import java.io.
BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.stream.
Collectors;import javax.servlet.
http.HttpServletResponse;import org.
apache.commons.lang3.StringUtils;
import org.springframework.beans.
factory.annotation.Value;import org.
springframework.web.bind.annotation.
RequestMapping;import org.springframework.
web.bind.annotation.RequestMethod;import org.
springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.
ResponseBody;import org.springframework.web.
bind.annotation.RestController;import org.
springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.
mvc.support.RedirectAttributes;import com.
vinord.common.model.ResultView;import com.
vinord.common.util.Constains;@RestController
public class FileUploadController
{
    @Value("${upload_path}")
    private final String upload_path ="D:/file_statics";

    @Value("${download_path}")
    private final String download_path ="D:/file_statics";

    /**
     * 单个文件上传
     * @param file
     * @param redirectAttributes
     * @return
     */
    @RequestMapping("uploadFile")
    public ResultView singleFileUpload(@RequestParam("file") 
    MultipartFile file,RedirectAttributes redirectAttributes) {
        ResultView result = new ResultView();
        if (file.isEmpty()) {
            redirectAttributes.addFlashAttribute("message", "请选择文件进行上传");
            result.setCode(Constains.STATUS_ZERO);
            result.setMsg("请选择文件进行上传!");
            return result;
        }

        try {
            byte[] bytes = file.getBytes();

            String filename = file.getOriginalFilename();
            String name = filename.substring(0,filename.lastIndexOf("."));
            String formatDate = System.currentTimeMillis()+"";
            int index = filename.indexOf(".");
            String savefilename = name + formatDate+ filename.substring(index);

            Path path = Paths.get(upload_path+ File.separator+savefilename);
            Files.write(path, bytes);

            redirectAttributes.addFlashAttribute("message","成功上传文件: '" + file.getOriginalFilename() + "'");

            result.setCode(Constains.STATUS_ONE);
            result.setMsg("上传成功");
        } catch (IOException e) {
            e.printStackTrace();
        }

        return result;
    }    /**
     * 多个文件上传
     * @param files
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/upload/batch", method = RequestMethod.POST)
    public ResultView batchUpload(@RequestParam("files")MultipartFile[] files) {
        ResultView result = new ResultView();

        String uploadedFileName = Arrays.stream(files).map(x -> x.getOriginalFilename())    
                    .filter(x -> !StringUtils.isEmpty(x)).collect(Collectors.joining(" , "));
        if (StringUtils.isEmpty(uploadedFileName)) {
            result.setCode(Constains.STATUS_ZERO);
            result.setMsg("文件上传失败,文件为空!");
            return result;
        }


        try {
            saveUploadedFiles(Arrays.asList(files));
        } catch (IOException e) {
            result.setCode(Constains.STATUS_ZERO);
            result.setMsg("文件上传异常"+e.getMessage());
            return result;
        }

        result.setCode(Constains.STATUS_ONE);
        result.setMsg("上传成功");
        return result;
    }


    private  void saveUploadedFiles(List<MultipartFile> files) throws IOException {
        for (MultipartFile file : files) {
            if (file.isEmpty()) {
                continue;
            }
            byte[] bytes = file.getBytes();

            String filename = file.getOriginalFilename();
            String name = filename.substring(0,filename.lastIndexOf("."));
            String formatDate = System.currentTimeMillis()+"";
            int index = filename.indexOf(".");
            String savefilename = name + formatDate+ filename.substring(index);

            Path path = Paths.get(upload_path+ File.separator+ savefilename);
            Files.write(path, bytes);
        }
    }    /**
     * 下载
     * @param res
     * @throws IOException
     */
    @RequestMapping("download")  
    public void download(HttpServletResponse res) throws IOException {

        String fileName = "CustomLogControl1536898060373.java";
        res.setHeader("content-type", "application/octet-stream");
        res.setContentType("application/octet-stream");
        res.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        byte[] buff = new byte[1024];
        BufferedInputStream bis = null;
        OutputStream os = null;
        try {
            os = res.getOutputStream();
            bis = new BufferedInputStream(new FileInputStream(new File(download_path+ File.separator+fileName)));
            int i = bis.read(buff);
            while (i != -1) {
                os.write(buff, 0, buff.length);
                os.flush();
                i = bis.read(buff);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


}
Nach dem Login kopieren

Verwandte Empfehlungen:

SpringBoot+Thymeleaf implementiert die Einführung von HTML-Dateien (ähnlich der Include-Funktion)_html/css_WEB-ITnose

Elegante Verwendung von mybatis

Das obige ist der detaillierte Inhalt vonSo erstellen Sie Springboot-Upload-Dateien. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Verwandte Etiketten:
Quelle:php.cn
Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!