java接收ajax上传文件_ajax & java文件上传

传统文件上传

导入jar包:commons-fileupload, commons-io

commons-fileupload

commons-fileupload

1.3.1

commons-io

commons-io

2.4

在前端提供一个form表单和文件选择域

编写controller

@RequestMapping("/fileupload")

public String fileupload(HttpServletRequest request){

//上传的位置(上传后保存的位置)

String path = request.getSession().getServletContext().getRealPath("/uploads");

File file = new File(path);

if(!file.exists()){//如果路径不存在

file.mkdirs();//创建文件夹

}

//解析request对象,获取上传文件项

DiskFileItemFactory factory = new DiskFileItemFactory();

ServletFileUpload upload = new ServletFileUpload(factory);

//解析request

List items = upload.parseRequest(request);

for(FileItem item: items){

if(item.isFormFiled){//如果是普通表单项

//TODO

}else{//如果是上传文件项

String filename = item.getName();//获取上传文件的名称

//可选:设置名称为唯一值

String uuid = UUID.randomUUID().toString().replace("-", "");

filename = uuid+"_"+filename;

item.write(new File(path, filename));//完成文件上传

item.delete();//删除临时文件(清理垃圾)

}

}

}

注意事项

form表彰的enctype取值必须是:multipart/form-data(用分隔符将表彰内容分隔成多个部分),默认为application/x-www-form-urlencoded(普通键值对的形式)

method属性值为Post

SpringMVC 上传文件

配置文件解析器

在前端提供一个form表单和文件选择域(name值与controller的文件参数保持一致)

编写controller

@RequestMapping("/fileupload")

public String fileupload(HttpServletRequest request, MultipartFile upload) throws Exception{

//上传的位置(上传后保存的位置)

String path = request.getSession().getServletContext().getRealPath("/uploads");

File file = new File(path);

if(!file.exists()){//如果路径不存在

file.mkdirs();//创建文件夹

}

String filename = upload.getOriginalFilename();//获取上传文件的名称

//可选:设置名称为唯一值

String uuid = UUID.randomUUID().toString().replace("-", "");

filename = uuid+"_"+filename;

upload.transferTo(new File(path, filename));//完成文件上传,不用删除临时文件

}

Ajax上传,Springboot接收

html

上传

js(使用FormData存放表单数据)

function uploadFile() {

var files = document.getElementById("upload").files;

var formdata = new FormData();

formdata.append("upload",files[0]);

$.ajax({

url:"/testUpload",

type:"post",

data:formdata,

contentType:false, //- 必须false才会自动加上正确的Content-Type

processData: false, //- 必须false才会避开jQuery对 formdata 的默认处理,XMLHttpRequest会对 formdata 进行正确的处理

success:function(){

alert("success");

},

error:function(){

alert("error");

}

});

}

Springboot Controller

@RequestMapping("/testUpload")

@ResponseBody

public String testUpload(@RequestParam("upload") MultipartFile upload){

System.out.println(upload.getOriginalFilename());

return "";

}

加载本地资源并返回给页面

Springboot

@RequestMapping("/imgurl")

@ResponseBody

public String createFolw(HttpServletResponse response) {

// response.setContentType("image/*");

FileInputStream fis = null;

OutputStream os = null;

try {

fis = new FileInputStream("D:/wechat.jpg");

os = response.getOutputStream();

int count = 0;

byte[] buffer = new byte[1024 * 8];

while ((count = fis.read(buffer)) != -1) {

os.write(buffer, 0, count);

os.flush();

}

} catch (Exception e) {

e.printStackTrace();

}

try {

fis.close();

os.close();

} catch (IOException e) {

e.printStackTrace();

}

return "ok";

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值