当前位置:网站首页>JS upload file method
JS upload file method
2022-07-28 07:20:00 【▀】
One . platform Environmental Science
win10 IDEA JDK8 springboot
Two . Upload files
Mode one FormData
1.WebConfig.java ( and Application.java In the same directory )
effect The local path D:\\upload\xxxxxxx Mapping to 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. Define the method in serviceimpl(/com/xxxxx/service) Class
@Override
public HigherResponse<String> addOneImage(HttpSession session, Product product, MultipartFile file) {
// Determine whether the file is in picture format
String originalFilename = file.getOriginalFilename();
if(!originalFilename.endsWith(".jpg") && !originalFilename.endsWith(".png")) {
return HigherResponse.getFailedRespon(" The picture format is not correct ");
}
String[] imgs = originalFilename.split("\\.");
// The name of the generated main graph The suffix of the picture
UUID uid = UUID.randomUUID();
String mainImage = uid+"."+imgs[1];
product.setMainImage(mainImage);
// Add product information to the database
int addOneProduct = productDao.addOneProduct(product);
if(addOneProduct == 0) {
return HigherResponse.getFailedRespon(" Upload image failed ");
}
try {
file.transferTo(new File("D:\\upload\\"+mainImage));
} catch (IllegalStateException e) {
return HigherResponse.getFailedRespon(" Upload image failed ");
} catch (IOException e) {
return HigherResponse.getFailedRespon(" Upload image failed ");
}
return HigherResponse.getSuccessRespon(" Upload successful ");
}3. Front page ( Refer to 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"> Submit </button>
<img id="im"/>
<script>
$('#b1').click(function () {
// 1. Master as one formdata object
var myFormData = new FormData();
// 2. Add normal key values to the object
// myFormData.append('username',$("#t1").val());
// myFormData.append('password',$("#t2").val());
// 3. Add file data to the object
// 1. Through the first jquery Find the tag
// 2. take jquery Object is converted to native js object
// 3. Use native js Object method Get the file content directly
myFormData.append('file',$('#exampleimg')[0].files[0]);
$.ajax({
url:'/manage/order/get_file.do',
type:'post',
data:myFormData, // Lose the object directly
// ajax Transfer files Be sure to specify two key parameters
contentType:false, // Without any coding because formdata The object has its own code django Be able to recognize the object
processData:false, // Tell the browser not to process my data Just send it directly
success:function (data) {
alert(data)
}
})
})
</script>
</body>
</html>4 effect


Mode two Turn the picture into base64 And then use json delivery ( Similar to sending a string )
<!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"> Submit </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', // modify url
type:'post',
dataType:"json",
data:{
file:baseurl
}, // Lose the object directly
// ajax Transfer files Be sure to specify two key parameters
success:function (data) {
alert(data)
}
})
})
</script>
</body>
</html>What will be obtained base64 Convert code to picture


边栏推荐
猜你喜欢

MHA高可用配置及故障切换

Not used for the longest time recently

Static and floating routes

Leetcode then a deep copy of the linked list

浅谈深分页问题

Earliest deadline first (EDF)

guava之限流RateLimiter

Current limiting ratelimiter of guava

Easypoi one to many, merge cells, and adapt the row height according to the content

High performance memory queue -disruptor
随机推荐
Heroku operation summary
map使用tuple实现多value值
Pytorch - storage and loading model
caffe fine tune
Tailing microelectronics B91 general development board integrated into the trunk of openharmony community
js二级联动院系
VNC Timed out waiting for a response from the computer
Standard C language learning summary 8
Tutorial on regularization
Layer 3 switching and VRRP
Standard C language learning summary 5
OJ questions about fast and slow pointers in linked lists
[a little knowledge] AQS
Log in to Oracle10g OEM and want to manage the monitor program, but the account password input page always pops up
High response ratio first
Redis sentinel mode and cluster
build_ opencv.sh
PyTorch - Dropout: A Simple Way to Prevent Neural Networks from Overfitting
2018-cvpr-Gesture Recognition: Focus on the Hands
Standard C language summary 1