- 在项目中,上传文件一般是必不可少的,所以今天学到新的上传方式,就干脆将学习过的上传方式记录一下
一、表单直接上传图片
- 表单头要设置
<form action="" method="post" enctype="multipart/form-data">
- 元素
<input type="file" name="dwfile" >
-
后端代码
@RequestMapping(value="addDownload",method=RequestMethod.POST)
public String addDownload(HttpServletRequest request,Model model,download download)throws Exception{
log.info("上传文件");
try{
String fileName = download.getDwfile().getOriginalFilename();
System.out.println("原始文件名:" + fileName);
// 新文件名
//String newFileName = UUID.randomUUID() + fileName;
// 获得项目的路径
ServletContext sc = request.getSession().getServletContext();
// 上传位置
String path = sc.getRealPath("/upload") + "/"; // 设定文件保存的目录
System.out.println(path);
File f = new File(path);
if (!f.exists())
f.mkdirs();
if (!download.getDwfile().isEmpty()) {
FileOutputStream fos = new FileOutputStream(path + fileName);
InputStream in = download.getDwfile().getInputStream();
int b = 0;
while ((b = in.read()) != -1) {
fos.write(b);
}
fos.close();
in.close();
}
download.setDwFile(fileName);
downloadService.insertSelective(download); }catch(Exception e){
System.out.println(e);
}
return "redirect:showDownload";
}二、使用ajax上传
1.通过jquery的插件jquery.form.js
- jsp页面代码
<form id="form111" name="form111" action="${path }/brand/addBrand.do" method="post" enctype="multipart/form-data">
<input type='file' size='27' id='imgsFile' name='imgsFile' class="file" onchange='submitUpload()' /> -
js代码
<script type="text/javascript" src="<c:url value='/{system}/res/js/jquery.form.js'/>"></script>
function submitUpload(){
var option = { url:"{path}/upload/uploadPic.do",//如果不指定url那么就使用使用提交表单的url,如果指定就使用当前的url
dataType:"text",
success:function(responseText){
var jsonObj = .parseJSON(responseText);("#imgsImgSrc").attr("src", jsonObj.realPath);
$("#imgs").val(jsonObj.relativePath); },
error:function(){
alert("系统错误");
}
};
$("#form111").ajaxSubmit(option); } - 后端接收
@RequestMapping("/uploadPic.do")
public void uploadPic(HttpServletRequest request, Writer out) throws IOException{
//把request转换成复杂request
MultipartHttpServletRequest mr = (MultipartHttpServletRequest) request;
//获得文件
Map<String, MultipartFile> map = mr.getFileMap();
Set<String> set = map.keySet();
Iterator<String> it = set.iterator();
String fileInputName = it.next();
MultipartFile mf = map.get(fileInputName);
//获得文件的字节数组
byte [] bs = mf.getBytes();
String fileName = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
Random random = new Random();
for(int i = 0; i < 3; i++){
fileName = fileName + random.nextInt(10);
} String oriFileName = mf.getOriginalFilename();
//获得文件的后缀
String suffix = oriFileName.substring(oriFileName.lastIndexOf("."));
//获得上传文件的绝对路径(上传和展示)
String realPath = ECPSUtils.readProp("file_path")+"/upload/"+fileName+suffix;
//获得相对路径(存储在数据库)
String relativePath = "/upload/"+fileName+suffix;
//创建jersy的客户端
Client client = Client.create();
//创建web资源对象
WebResource wr = client.resource(realPath);
//上传
wr.put(bs);
JSONObject jo = new JSONObject();
jo.accumulate("realPath", realPath);
jo.accumulate("relativePath", relativePath);
String result = jo.toString();
out.write(result);
}2.使用FormData对象
- 这种还没有使用过,以后研究
ajax基本使用json数据
相关文章
- 项目中常用到的前端vue根据后端接口返回文件地址实现在线预览和下载功能
- 搭建一个maven管理的ssm项目需要配置那些文件
- iOS项目中常见的文件
- Maven的SSM项目常用配置文件pom.xml
- 使用IntelliJ IDEA创建Maven聚合工程、创建resources文件夹、ssm框架整合、项目运行一体化
- 【转载】使用IntelliJ IDEA创建Maven聚合工程、创建resources文件夹、ssm框架整合、项目运行一体化
- SSM框架搭建,相关配置文件编写--非分布式电商项目(继续)
- Extjs 项目中常用的小技巧,也许你用得着(5)--设置 Ext.data.Store 传参的请求方式
- iOS开发中常见的项目文件与MVC结构优化思路解析
- SSM框架搭建,相关配置文件编写--非分布式电商项目(完结)