当前位置:网站首页>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编码转换成图片


边栏推荐
- Differences and relationships among NPM, Yran and NPX
- Three cache technologies -- localstorage, sessionstorage, cookies
- Circular linked list problem
- MOOC翁恺 C语言 第三周:判断与循环:1.判断
- MOOC Weng Kai C language week 5: 1. cycle control 2. multiple cycles 3. cycle application
- Sysevr environment configuration: joern-0.3.1, neo4j-2.1.5, py2neo2.0
- bond模式配置
- DOM - Events
- RAID磁盘阵列
- 登录进oracle10g的oem,想管理监听程序却总是弹出帐号密码输入页面
猜你喜欢

win下安装nessus

Detailed explanation of active scanning technology nmap

Layer 3 switching and VRRP

codesensor:将代码转化为ast后再转化为文本向量

PXE无人值守安装管理

爬虫学习总结

MOOC Weng Kai C language fourth week: further judgment and circulation: 3. Multiple branches 4. Examples of circulation 5. Common errors in judgment and circulation

DNS domain name resolution

ELK日志分析系统的部署

Sysevr environment configuration: joern-0.3.1, neo4j-2.1.5, py2neo2.0
随机推荐
Detailed explanation of active scanning technology nmap
MOOC Weng Kai C language fourth week: further judgment and circulation: 3. Multiple branches 4. Examples of circulation 5. Common errors in judgment and circulation
Neo4j running error occurred during initialization of VM incompatible minimum and maximum heap sizes spec
Blue Bridge Cup square filling number
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
MOOC翁恺C语言 第四周:进一步的判断与循环:1.逻辑类型与运算2.级联和嵌套的判断
MySQL queries all descendant nodes under the parent node. When querying the user list, it is processed by multi-level (company) departments. According to reflection, it recurses the tree structure too
Uni app double click event simulation
Results fill in the blanks carelessly (violent solution)
MOOC Weng Kai C language week 8: pointer and string: 1. Pointer 2. Character type 3. String 4. String calculation
Install Nessus under win
Pictures are adaptive to the screen
Blue bridge code error ticket
视频格式基础知识:让你了解MKV、MP4、H.265、码率、色深等等
MOOC Weng Kai C language fourth week: further judgment and circulation: 1. Logical types and operations 2. Judgment of cascading and nesting
MySQL build database Series (I) -- download MySQL
Softmax multi classification gradient derivation
DNS域名解析
Standard C language learning summary 8
freemarker导出word,带表格和多张图片,解决图片重复和变形