手写upload方法,将文件放到服务器的指定位置

 

简单的上传文件,不约束上传文件的类型,均可进行上传操作.

 

尤其是前后端前后端代码分离的时候,前后端代码的联调很让人奔溃的,所以将前台代码也贴出来了..供大家使用...

 

<!DOCTYPE html> 
<html> 
<head lang="en"> 
    <meta charset="UTF-8"> 
    <script src="./jquery-1.11.1.min.js"></script>
    <title></title> 
</head> 
 <body> 
    <form id="uploadForm" enctype="multipart/form-data"> 
        文件:<input id="file" type="file" name="与后台接收一致"/> 
    </form> 
    <button id="upload">上传文件</button> 
</body> 
<script type="text/javascript"> 
    $(function () { 
        $("#upload").click(function () { 
            var formData = new FormData($('#uploadForm')[0]); 
            $.ajax({ 
                type: 'post', 
                url: "http://localhost:18010/file/fileUpload", 
                data: formData, 
                cache: false, 
                processData: false, 
                contentType: false, 
                success:function (data) { 
                    alert(data); 
                },
                error:function () { 
                    alert("上传失败"); 
                }
            });
        }); 
    });
</script>
</html>

可是js文件还是没有办法上传,所以更尴尬....(js就真的不传了..)

后台暴露接口为:

package com.young.springdemo.controller;

import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

//文件上传和下载接口
@RestController
@RequestMapping(value = "file")
@CrossOrigin
public class FileUploadController {

    @RequestMapping(value = "fileUpload",method = RequestMethod.POST)
    public String fileUpload(@RequestParam("formData") MultipartFile file){
        if(file.isEmpty()){
            return "false";
        }
        String fileName = file.getOriginalFilename();
        int size = (int) file.getSize();
        System.out.println(fileName + "-->" + size);

        String path = "E:/test" ;
        File dest = new File(path + "/" + fileName);
        if(!dest.getParentFile().exists()){ //判断文件父目录是否存在
            dest.getParentFile().mkdir();
        }
        try {
            file.transferTo(dest); //保存文件
            return "true";
        } catch (IllegalStateException e) {
            e.printStackTrace();
            return "false";
        } catch (IOException e) {
            return "false";
        }
    }

    @RequestMapping(name = "/download",method = RequestMethod.GET)
    public String downLoad(HttpServletResponse response,@RequestParam("path")String path) throws UnsupportedEncodingException {
        String filename="nacos_config_export_2020-01-02 21_47_46.zip";
        String filePath = "E:/test" ;
        File file = new File(filePath + "/" + filename);
        System.out.println("下载"+filename+"路径="+path);
        if(file.exists()){ //判断文件父目录是否存在
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
            // response.setContentType("application/force-download");
            response.setHeader("Content-Disposition", "attachment;fileName=" +   java.net.URLEncoder.encode(filename,"UTF-8"));
            byte[] buffer = new byte[1024];
            FileInputStream fis = null; //文件输入流
            BufferedInputStream bis = null;

            OutputStream os = null; //输出流
            try {
                os = response.getOutputStream();
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                int i = bis.read(buffer);
                while(i != -1){
                    os.write(buffer);
                    i = bis.read(buffer);
                }

            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println("----------file download---" + filename);
            try {
                bis.close();
                fis.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return null;
    }
}

其他的具体配置,文件路径或者上传文件大小限制什么之类的,可以后期自己慢慢维护....

所以该Controller在swagger中是可以暴露的,且正常上传没问题...然后该html文件,在chrome中执行也没问题的...所以接口都是没问题的.....

但是在项目使用过程中,突然出现一个点击调用该接口,然后session就丢了,客户直接退出页面了....

这是正常现象,可以到权限的地方,把该应用的filter过滤掉,直接进行...(这个可以考虑get方式的请求处理)

 

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