- 文件上传
导包
|
|
|
|
Springmvc.xml配置支持文件上传
|
|
Html/JS
第一种(失败了)
|
|
|
|
|
|
第二种:
<%--
Created by IntelliJ IDEA.
User: gyf
Date: 2018/5/25
Time: 10:25
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<script src="${pageContext.request.contextPath}/js/jquery-1.8.3.js"></script>
<script src="${pageContext.request.contextPath}/js/jquery.form.js"></script>
<title>编辑商品</title>
<script type="text/javascript">
function sumbitImage() {
alert("提交图片到后台");
var dataoptions={
type:'post',
url:'${pageContext.request.contextPath}/upload/itemspic.do',
success:function (respData) {
//var jsonObj = $.parseJSON(respData);
var obj =JSON.parse(respData);
$('#pic').attr('src',obj.imgUrl);
console.log(obj.imgUrl);
$('#hiddenPic').val(obj.imgUrl)
}
}
$('#itemsForm').ajaxSubmit(dataoptions)
}
</script>
</head>
<body>
<form id="itemsForm" action="${pageContext.request.contextPath}/items/update.do" method="post">
<table border="1">
<tr>
<td>名称</td>
<td>
<input type="text" name="name" value="${items.name}"></td>
<input type="hidden" name="id" value="${items.id}"></td>
</tr>
<tr>
<td>价格</td>
<td><input type="text" name="price" value="${items.price}"></td>
</tr>
<tr>
<td>描述</td>
<td><textarea cols="20" rows="5" name="detail">${items.detail}</textarea></td>
</tr>
<tr>
<td>图片</td>
<td>
<img id="pic" src="${items.pic}" width="100px" height="100px">
<input type="file" name="itemspic1" οnchange="sumbitImage();">
<input id="hiddenPic" type="hidden" name="pic" value="${items.pic}">
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="更新">
</td>
</tr>
</table>
</form>
</body>
</html>
后台
第一种(没采用)
|
@Controller @RequestMapping("upload") public class UploadController { @RequestMapping("itemsPic") public void itemsPic(HttpServletRequest request,String fileName, PrintWriter writer) throws Exception{ MultipartHttpServletRequest mulRequest = (MultipartHttpServletRequest) request; //通过字段名获取文件数据 MultipartFile file1 = mulRequest.getFile(fileName);
System.out.println(fileName + ":上传文件大小 " + file1.getSize());
//格式化文件名 SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS"); String saveName = sdf.format(new Date()); Random rd = new Random(); for(int i=0;i<3;i++){ saveName += rd.nextInt(10);//添加三个随机数 }
//文件后缀名 String suffix = file1.getOriginalFilename().split("\\.")[1];
String saveFileName = saveName + "." + suffix;
//文件保存目录 String dir = request.getServletContext().getRealPath("/upload"); File dirFile = new File(dir); if(dirFile.exists() == false)dirFile.mkdirs();
//文件保存路径 String relativePath = "/upload/" + saveFileName; String totalPath = request.getServletContext().getRealPath(relativePath); System.out.println(totalPath);
File newFile = new File(totalPath);
//保存 FileCopyUtils.copy(file1.getInputStream(), new FileOutputStream(newFile)); Thread.sleep(2000); //file1.transferTo(newFile);
//返回一个相对路径 相对路径和全路径 String serverIp = "http://127.0.0.1:8080" + request.getServletContext().getContextPath(); String respJson = "{\"imgUrl\":\"" + serverIp + relativePath+"\"}";
writer.write(respJson); } } |
第二种:
package com.dong.backoffice.web.controller;
import com.dong.backoffice.model.Items;
import com.dong.backoffice.service.IItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.Date;
import java.util.List;
import java.util.UUID;
@Controller
@RequestMapping("upload")
public class UpdateLoadController {
@Autowired
private IItemService iItemService;
@RequestMapping("itemspic")
public void itemspic(HttpServletRequest request, HttpServletResponse response) throws Exception {
MultipartHttpServletRequest multipartHttpServletRequest= (MultipartHttpServletRequest) request;
//1.获取图片数据
MultipartFile multipartFile=multipartHttpServletRequest.getFile("itemspic1");
//2.把图片保存在某个路径
//2.1文件保存的文件夹路径
String uploadFolder=request.getServletContext().getRealPath("/upload");
File file=new File(uploadFolder);
if(!file.exists()){
file.mkdirs();
}
//2.2.文件
// 获取图片后缀
String suffix=multipartFile.getOriginalFilename().split("\\.")[1];
String fileName= UUID.randomUUID().toString().replace("-","")+"."+suffix;
String totalPath = uploadFolder + "\\" + fileName;
FileCopyUtils.copy(multipartFile.getInputStream(),new FileOutputStream(new File(totalPath)));
//返回数据给客户端
String imgURL = "http://localhost:8088/SSSMDemo/upload/" + fileName;
String responseJson = "{\"imgUrl\":\"" + imgURL + "\"}";
response.setHeader("content-Type","text/html;charset=utf-8");
System.out.println(responseJson);
response.getWriter().write(responseJson);
}
}