第一种,前后端分离,前端采用vue+element
逻辑:通过前端上传图片到后端,后端将其保存到服务器,并将其保存路径及其他信息返回给前端,前端再将该图片路径及其学生信息一起提交 StuAdd.vue
<template>
<el-card class="box-card">
<el-form ref="form" :model="stu" label-width="80px">
<el-form-item label="选择头像">
<el-upload
class="upload-demo"
action="http://localhost:9999/stu/stu/addPic"
:on-success="handleSuccess"
:file-list="fileList"
list-type="picture">
<el-button size="small" type="primary">点击上传</el-button>
<div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>
</el-upload>
</el-form-item>
<el-form-item label="姓名">
<el-input v-model="stu.name"></el-input>
</el-form-item>
<el-form-item label="年龄">
<el-input v-model="stu.age"></el-input>
</el-form-item>
<el-form-item label="邮箱">
<el-input v-model="stu.email"></el-input>
</el-form-item>
<el-form-item label="生日">
<el-col :span="12">
<el-date-picker type="date" placeholder="选择日期" v-model="stu.birth" style="width: 100%;"></el-date-picker>
</el-col>
</el-form-item>
<el-form-item label="所在学校">
<el-select v-model="stu.schid" placeholder="活动区域">
<el-option v-for="(item,index) in schs" :label="item.name"
:value="item.id" :key="index"></el-option>
</el-select>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="addStu">立即创建</el-button>
<el-button>取消</el-button>
</el-form-item>
</el-form>
</el-card>
</template>
<script>
export default {
name:'app',
data(){
return{
stu:{
name:'',
age:'',
birth:'',
email:'',
schid:'',
pics:[],
savepath:[],
realname:[],
uploadtime:[],
},
schs:[],
fileList:[],
}
},
methods:{
handleSuccess(response,file,fileList){
this.stu.pics.push(response.data)
this.stu.savepath.push(response.data.savepath)
this.stu.realname.push(response.data.realname)
this.stu.uploadtime.push(response.data.uploadtime)
},
addStu(){
this.$http.post('/stu/addStu',
this.$qs.stringify(this.stu,{allowDots:true,arrayFormat:'repeat'}))
.then(response=>{
}).catch(error=>console.log('出错了:'+error))
},
queryAllSchs(){
this.$http.get('/stu/queryAllSch')
.then(response=>{
this.schs = response.data.data
}).catch(error=>console.log('出错了:'+error))
},
},
created(){
this.queryAllSchs()
}
}
</script>
<style lang="less" scoped>
</style>
其中 :on-success="handleSuccess" 表示上传成功后执行的方法,主要是将图片存储路径返回给该vue容器
- 第一种后台处理代码:采用servlet处理请求,fileupload处理上传,fastjson处理json格式返回
- 导入文件上传依赖
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.74</version>
</dependency>
- 代码
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import com.alibaba.fastjson.JSONArray;
@WebServlet("/addpic")
public class PicServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
FileItemFactory f = new DiskFileItemFactory();
ServletFileUpload su = new ServletFileUpload(f);
try {
List<FileItem> items = su.parseRequest(req);
for (FileItem item : items) {
if (!item.isFormField()) {
String fileName = item.getName();
String fExt = fileName.substring(fileName.lastIndexOf("."));
String newName = UUID.randomUUID().toString().replaceAll("-","")+fExt;
ServletContext application = this.getServletContext();
String path = application.getRealPath("/files");
File parent = new File(path);
if (!parent.exists()) {
parent.mkdir();
}
File file = new File(parent,newName);
item.write(file);
Pic pic = new Pic();
pic.setRealname(fileName);
pic.setSavepath("/files/"+newName);
pic.setUploadtime(new Timestamp(System.currentTimeMillis()));
pic.setFlag(0);
JsonResponse jr = new JsonResponse();
jr.setCode(200);
jr.setMsg("success");
jr.setData(pic);
resp.setContentType("text/plain;charset=UTF-8");
PrintWriter out = resp.getWriter();
String str = JSONArray.toJSONString(jr);
out.print(str);
out.flush();
out.close();
}
}
}catch (Exception e){
e.printStackTrace();
}
}
}
- 导入依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.8</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
- springmvc.xml文件中配置
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="10485760"/>
</bean>
- 代码
import org.springframework.web.multipart.MultipartFile;
@RestController
@RequestMapping("/stu")
public class StudentController {
@PostMapping("/addPic")
public JsonResponse addPic(MultipartFile file,HttpServletRequest req){
String fileName = file.getOriginalFilename();
String fExt = fileName.substring(fileName.lastIndexOf("."));
String newName = UUID.randomUUID().toString().replaceAll("-","")+fExt;
ServletContext application = req.getServletContext();
String path = application.getRealPath("/files");
File parent = new File(path);
if(!parent.exists()){
parent.mkdir();
}
File f = new File(parent,newName);
try {
file.transferTo(f);
} catch (IOException e) {
e.printStackTrace();
}
Pic pic = new Pic();
pic.setRealname(fileName);
pic.setSavepath("/files/"+newName);
pic.setUploadtime(new Timestamp(System.currentTimeMillis()));
pic.setFlag(0);
JsonResponse jr = new JsonResponse();
jr.setCode(200);
jr.setMsg("添加成功");
jr.setData(pic);
return jr;
}
@PostMapping("/addStu")
public JsonResponse addStu(StudentVo vo){
Student stu = new Student();
BeanUtils.copyProperties(vo,stu);
service.addStuAndPic(stu,vo);
return null;
}
}
图片实体类
import java.sql.Timestamp;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Pic {
private Integer id;
private String savepath;
private String realname;
private Timestamp uploadtime;
private Integer stuid;
private Integer flag;
}
学生实体类
public class Student {
private Integer id;
private String name;
private Integer age;
@DateTimeFormat(pattern = "yyyy-MM-dd")
@JsonFormat(pattern = "yyyy-MM-dd")
private Date birth;
private String email;
private Integer schid;
private School sch;
}
学生传输类
public class StudentVo {
private Integer pageNumber;
private Integer pageSize;
private String name;
private Integer age;
private String email;
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date birth;
private Integer schid;
private String[] birth1;
private String startbirth;
private String endbirth;
private String[] savepath;
private String[] realname;
private String[] uploadtime;
}
第二种:自己编写的文件上传工具,仅供参考
@Controller
@RequestMapping("/user")
public class UserController {
@RequestMapping(path = "/register",method = {RequestMethod.POST})
public String register(User user,MultipartFile upload,String check) throws IOException {
User user2 = iUserService.findUserByUsername(user.getUsername());
if (user2 == null){
String fileName = FileUploadUtils.fileUploadUtil(upload,"user",request);
user.setUserIcon(fileName);
return "redirect:/register-ok.jsp";
}else {
request.setAttribute("registerInfo","该用户名已被注册");
return "forward:/register.jsp";
}
}
}
package cn.cyl.utils.fileupload;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.Properties;
import java.util.UUID;
public class FileUploadUtils {
private static Properties properties;
private static String nativePath;
static {
properties = new Properties();
InputStream in = FileUploadUtils.class.getClassLoader().getResourceAsStream("fileupload.properties");
try {
properties.load(in);
} catch (IOException e) {
e.printStackTrace();
}
nativePath = properties.getProperty("fileurl");
}
public static String fileUploadUtil(MultipartFile upload,String smallPath,HttpServletRequest request) throws IOException {
String filename = upload.getOriginalFilename();
if (filename==""){
if (smallPath=="user"){
filename = properties.getProperty("defaultUser");
}
if (smallPath=="found"){
filename = properties.getProperty("defaultFound");
}
if(smallPath=="lost"){
filename = properties.getProperty("defaultLost");
}
}else {
String path = request.getSession().getServletContext().getRealPath("/images/"+smallPath);
File file = new File(path);
if (!file.exists()){
file.mkdirs();
}
String uuid = UUID.randomUUID().toString().replace("-","");
filename = uuid+"_"+filename;
inputStreamToFile(upload.getInputStream(), new File(nativePath+smallPath+"\\"+filename));
upload.transferTo(new File(path,filename));
}
return "images/"+smallPath+"/"+filename;
}
public static void inputStreamToFile(InputStream ins, File file) {
try {
OutputStream os = new FileOutputStream(file);
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
ins.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
|