您现在的位置是:首页 > 个人日记个人日记
springMVC-07-文件上传
2019-02-14 18:20:03【个人日记】983人已围观
简介springMVC的文件上传,使用更加方便
文件上传
创建文件上传类
package com.huangxin.order.controller;
import com.huangxin.order.service.FileService;
import com.huangxin.order.uploadUtil.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
@Controller
public class UploadController {
@Autowired
private FileService fileService;
@GetMapping("/upload")
public String upload() {
return "upload/upload";
}
//单文件上传
@PostMapping("/upload")
@ResponseBody
public R upload(MultipartFile multipartFile) {
String str = fileService.upload(multipartFile);
return R.ok(str);
}
//多文件上传
@PostMapping("/uploads")
@ResponseBody
public R upload(@RequestParam("multipartFile") MultipartFile[] multipartFiles) {//多个文件上传
try {
for (MultipartFile multipartFile1 : multipartFiles) {
File file = new File("D:/" + multipartFile1.getOriginalFilename());
multipartFile1.transferTo(file);
}
} catch (Exception e) {
e.printStackTrace();
return R.error("文件上传失败");
}
return R.ok("文件上传成功");
}
}
工具类
package com.huangxin.order.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
public class FileService {
@Autowired
private HttpSession httpSession;
public String upload(MultipartFile multipartFile) {
String realPath = null;
try {
//拿到路径
realPath = httpSession.getServletContext().getRealPath("/");
File file = new File(realPath + multipartFile.getOriginalFilename());
multipartFile.transferTo(file);//保存文件
} catch (IOException e) {
e.printStackTrace();
}
return realPath;
}
}
Tags: JavaWeb
上一篇: mybatis-02-CRUD简单操作
下一篇: spring-04-对象注入
相关文章
随机图文
评论区
2024-10-08 04:12:16
站长
没有登录功能是为了方便大家留言,但留言接口现在被恶意攻击,将关闭留言接口,如有疑问,请联系我的QQ 1538933906/同微信