睿虎的博客

下面是用SpringBoot完成文件下载的代码:

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
29
30
31
32
33
@Controller
@RequestMapping("/download")
public class DownloadController {

@ResponseBody
@RequestMapping("/download")
public String fileDownLoad(HttpServletResponse response, @RequestParam("fileName") String fileName){
String downloadFilePath="D:\\laiscdata";
File file = new File(downloadFilePath +'\\'+ fileName);
if(!file.exists()){
return "下载文件不存在";
}
response.reset();
response.setContentType("application/octet-stream");
response.setCharacterEncoding("utf-8");
response.setContentLength((int) file.length());
response.setHeader("Content-Disposition", "attachment;filename=" + fileName );

try(BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));) {
byte[] buff = new byte[1024];
OutputStream os = response.getOutputStream();
int i = 0;
while ((i = bis.read(buff)) != -1) {
os.write(buff, 0, i);
os.flush();
}
} catch (IOException e) {
System.out.println("程序错误:"+e);
return "下载失败";
}
return "下载成功";
}
}

测试:访问http://localhost:8088/download/download?fileName=1.zip

下面是用SpringBoot完成文件上传的代码:

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
29
30
@Controller
@RequestMapping("/upload")
public class UploadController {

@ResponseBody
@RequestMapping("/upload")
public String httpUpload(@RequestParam("files") MultipartFile files[]){
String uploadFilePath="D:\\laiscdata";
JSONObject object=new JSONObject();
for(int i=0;i<files.length;i++){
String fileName = files[i].getOriginalFilename(); // 文件名
File dest = new File(uploadFilePath +'\\'+ fileName);
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
try {
files[i].transferTo(dest);
} catch (Exception e) {
System.out.println("程序错误:"+e);
object.put("success",2);
object.put("result","程序错误,请重新上传");
return object.toString();
}
}
object.put("success",1);
object.put("result","文件上传成功");
return object.toString();
}

}

上面的代码看起来有点多,其实就是一个上传的方法,首先通过 MultipartFile 接收文件。这里我用的是file[] 数组接收文件,这是为了兼容多文件上传的情况,如果只用file 接收,然后在接口上传多个文件的话,只会接收最后一个文件。这里大家注意一下。看自己的需求,我这里兼容多文件所以用数组接收。

Read more »

1
2
git config --global user.name "John Doe"
git config --global user.email johndoe@example.com

设置用户名称与邮件地址

1
git config --global core.editor "'C:\Program Files\Notepad++\notepad++.exe' -multiInst -notabbar -nosession -noPlugin"

设置默认文本编辑器

1
git config --list

列出所有 Git 当时能找到的配置

1
git init

在现有目录中初始化仓库

重点

1
2
git add *.c
git add LICENSE

开始对指定文件的跟踪
或 更新文件到暂存区

Read more »
0%