当前位置:网站首页>js上传文件的方式
js上传文件的方式
2022-07-28 05:30:00 【▀】
一 . 平台 环境
win10 IDEA JDK8 springboot
二 . 上传文件
方式一 FormData
1.WebConfig.java (和Application.java同一目录下)
作用 将本地路径 D:\\upload\xxxxxxx 映射成为 http://127.0.0.1:8080/upload/xxxxxxxx
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter{
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/upload/**").addResourceLocations("file:D:\\upload\\");
}
}2. 定义方法在 serviceimpl(/com/xxxxx/service)类中
@Override
public HigherResponse<String> addOneImage(HttpSession session, Product product, MultipartFile file) {
// 判断文件是否是图片格式
String originalFilename = file.getOriginalFilename();
if(!originalFilename.endsWith(".jpg") && !originalFilename.endsWith(".png")) {
return HigherResponse.getFailedRespon("图片格式不正确");
}
String[] imgs = originalFilename.split("\\.");
// 生成主图的名字 图片的后缀
UUID uid = UUID.randomUUID();
String mainImage = uid+"."+imgs[1];
product.setMainImage(mainImage);
// 往数据库添加商品信息
int addOneProduct = productDao.addOneProduct(product);
if(addOneProduct == 0) {
return HigherResponse.getFailedRespon("上传图片失败");
}
try {
file.transferTo(new File("D:\\upload\\"+mainImage));
} catch (IllegalStateException e) {
return HigherResponse.getFailedRespon("上传图片失败");
} catch (IOException e) {
return HigherResponse.getFailedRespon("上传图片失败");
}
return HigherResponse.getSuccessRespon("上传成功");
}3.前端页面(参考于 https://www.cnblogs.com/chanyuli/p/11761421.html)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
<link href="https://cdn.bootcss.com/twitter-bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.bootcss.com/twitter-bootstrap/3.3.1/js/bootstrap.min.js"></script>
</head>
<body>
<input type="file" name="file" id="exampleimg">
<button id="b1">提交</button>
<img id="im"/>
<script>
$('#b1').click(function () {
// 1.先生成一个formdata对象
var myFormData = new FormData();
// 2.朝对象中添加普通的键值
// myFormData.append('username',$("#t1").val());
// myFormData.append('password',$("#t2").val());
// 3.朝对象中添加文件数据
// 1.先通过jquery查找到该标签
// 2.将jquery对象转换成原生的js对象
// 3.利用原生js对象的方法 直接获取文件内容
myFormData.append('file',$('#exampleimg')[0].files[0]);
$.ajax({
url:'/manage/order/get_file.do',
type:'post',
data:myFormData, // 直接丢对象
// ajax传文件 一定要指定两个关键性的参数
contentType:false, // 不用任何编码 因为formdata对象自带编码 django能够识别该对象
processData:false, // 告诉浏览器不要处理我的数据 直接发就行
success:function (data) {
alert(data)
}
})
})
</script>
</body>
</html>4 效果


方式二 将图片转为base64然后使用json传送(类似于发送字符串)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
<link href="https://cdn.bootcss.com/twitter-bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.bootcss.com/twitter-bootstrap/3.3.1/js/bootstrap.min.js"></script>
</head>
<body>
<input type="file" name="file" id="exampleimg">
<button id="b1">提交</button>
<img id="im" style="width: 300px;height: 100%"/>
<script>
var baseurl = "";
document.getElementById('exampleimg').addEventListener("change",function(){
var target = document.getElementById("exampleimg").files[0];
var fileReader = new FileReader();
fileReader.readAsDataURL(target);
fileReader.onload = function(ex){
baseurl = ex.target.result;
document.getElementById("im").setAttribute("src",baseurl);
};
})
document.getElementById("b1").addEventListener("click",function (ev) {
window.console.log(typeof baseurl);
$.ajax({
url:'/manage/order/get_file02.do', //修改url
type:'post',
dataType:"json",
data:{
file:baseurl
}, // 直接丢对象
// ajax传文件 一定要指定两个关键性的参数
success:function (data) {
alert(data)
}
})
})
</script>
</body>
</html>将得到的base64编码转换成图片


边栏推荐
- Basic knowledge of video format: let you know MKV, MP4, h.265, bit rate, color depth, etc
- Bond mode configuration
- Shell --- conditional statement practice
- MySQL build database Series (I) -- download MySQL
- Metasploit penetration MS7_ 010 exercise
- Blueberry pie Bluetooth debugging process
- easypoi一对多,合并单元格,并且根据内容自适应行高
- Neo4j运行报错Error occurred during initialization of VM Incompatible minimum and maximum heap sizes spec
- Review of C language (byte alignment)
- easypoi导出表格带echars图表
猜你喜欢

MySQL查询父节点下面的所有子孙节点,查询用户列表时多级(公司)部门处理,根据反射,递归树形结构工具类

Canvas drawing 2

DNS域名解析

Circular linked list problem

A timed task reminder tool

DNS domain name resolution

Neo4j运行报错Error occurred during initialization of VM Incompatible minimum and maximum heap sizes spec

C language: understand the creation and destruction of function stack frames through an example

VNC Timed out waiting for a response from the computer

Softmax multi classification gradient derivation
随机推荐
Leetcode then a deep copy of the linked list
Pytorch installation - CPU version
JS array method Encyclopedia
Gobang optimized version
MySQL excludes holidays and calculates the date difference
Standard C language learning summary 6
Result fill in the blank (dfs*c language)
Remotely access the local website of services such as neo4j on the ECS
C language review (modifier article)
shell---条件语句练习
Freemaker exports word with tables and multiple pictures to solve the repetition and deformation of pictures
Open virtual machine kali2022.2 and install GVM
Monotonic queue, Luogu p1886 sliding window
静态和浮动路由
Read the IP and device information of the switch node in the XML file, Ping the device, and the exception is displayed in the list
VNC Timed out waiting for a response from the computer
Blueberry pie Bluetooth debugging process
kali下安装nessus
VNC Timed out waiting for a response from the computer
NAT-网络地址转换