![cover](https://img-blog.csdnimg.cn/direct/39c0f8d8c15e4a108ca32af7edf39a1b.png)
springboot form-data 1.图片上传笔记 2.Jackson库 json序列化反序列化笔记 3.通用对接代码记录
file-list绑定失效 直接用this.$refs.upload.uploadFiles?.[0]?.raw这个axios上传类似。
·
一、图片上传笔记
(1)图片上传客户端
file-list绑定失效(似乎只是一开始用来展示的,不能双向绑定) 直接用this.$refs.upload.uploadFiles?.[0]?.raw(点击上传图片后才会被初始化)
这个axios上传类似
(2)服务端
二、json序列化笔记
import com.fasterxml.jackson.databind.ObjectMapper;
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.76</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>2.13.0</version>
</dependency>
(1)代码VUE
// 序列化
JSON.stringify(myObject);
// 反序列化
const myObject = JSON.parse(jsonString);
(2)代码JAVA
ObjectMapper objectMapper = new ObjectMapper();
// 序列化
Product product = objectMapper.readValue(product_json, Product.class);
// 反序列化
String json_str = objectMapper.writeValueAsString(product);
(3)更高效方法?-1
@Transactional(rollbackFor = CustomException.class)
public Alipay updateByOne(Map<String,Object> params) throws Exception{
Alipay alipay = new Alipay();
/*
for (Map.Entry<String, Object> entry : params.entrySet()) {
log.info("Key: " + entry.getKey() + ", Value: " + entry.getValue());
}
*/
Order order = (Order)params.get("order");
Product db_product = (Product)params.get("db_product");
但是Map<String,Object> body = (Map<String,Object>)httpService.s.. 报错了 似乎不能转Map
(4)更高效方法?-2
JSONObject jsonObject = JSONObject.parseObject(jsonString);
String value1 = jsonObject.getString("key1");
int value2 = jsonObject.getInteger("key2");
@PostMapping("/login") // 登录 //session IsLogin判断状态
public R<String> UserLogin(@RequestBody String jsonString,HttpSession session){
JSONObject jsonObject = JSONObject.parseObject(jsonString);
User user = jsonObject.getObject("user",User.class);
String code = jsonObject.getString("code");
ObjectMapper objectMapper = new ObjectMapper();
Product product = new Product(1, "Apple");
// 将实体类转换为 Map
Map<String, Object> map = objectMapper.convertValue(product, Map.class);
json字符String转Map要用objectMapper.readValue 我也不知道为啥 不然报错
import com.alibaba.fastjson.JSONObject; 不用写Dto咯~~~~~
三、通用对接代码记录
(1)图片请求
前端发送
axios_add(){
//this.$refs.upload.submit();
let formData = new FormData()
formData.append('photo', this.$refs.upload.uploadFiles?.[0]?.raw)
formData.append('product_json',JSON.stringify(this.dialogdata2)) // 序列化
axios.post('/product/addonebyadmin',formData,{
headers: {
'Content-Type': 'multipart/form-data'
}
})
.then(response=>{
if(response.data.code===0)this.$message.error(response.data.msg)
else {
this.dialogVisible2 = false
this.$message.success("添加成功")
this.gettable()
}
}).catch(error=>{
this.$message.error(error.data.msg)
console.log(error)
})
}
JAVA接收图片请求
@PutMapping("/updateonebyadmin") // 更新一个商品 //不加注解默认form-data
public R<String> UpdateOneProduct(MultipartFile photo,String product_json,HttpSession session){
try{
ObjectMapper objectMapper = new ObjectMapper();
// 序列化
Product product = objectMapper.readValue(product_json, Product.class);
...
(2)GET请求 VUE JAVA
VUE一般请求
gettablebycondition(){
this.IsTableLoading = true
var page = {
currentPage: this.currentPage,
PageSize: this.PageSize
}
var params = {...page,...this.dialogdata3,'value2':this.value2}
console.log(params)
axios.get('/product/selectpagebyadmin',{
params: params
}).then(response=>{
if(response.data.code===0)this.$message.error(response.data.msg)
else {
this.tableData = response.data.data.records
this.TotalPage = response.data.data.total
this.IsTableLoading = false
//this.$message.success("获取成功")
// #region 获取筛选
var init_dialogdata3 = {};
for (let [key, value] of Object.entries(response.data.map)) {
if(key!=="currentPage" && key!=="PageSize" && key!=="value2"){
init_dialogdata3[key] = value
}
}
this.dialogdata3 = init_dialogdata3
// #endregion
// 初始化Tag
this.init_Tags()
}
}).catch(error=>{
this.$message.error(error.data.msg)
console.log(error)
})
},
生成的请求网址
http://localhost:9528/product/selectpagebyadmin?currentPage=1&PageSize=10&value2=a
后端接收
@GetMapping("/selectpagebyadmin") // 分页查询 接收params //防空设默认
public R<Page<Product>> FindPageProducts(@RequestParam Map<String, String> params, HttpSession session){
// 使用LambdaQueryChainWrapper构建查询
LambdaQueryChainWrapper<Product> query = new LambdaQueryChainWrapper<>(productmapper);
// 根据条件动态添加查询条件
if (params.get("name") != null) {
query.like(Product::getName, params.get("name"));
}
// 单独处理startDate,如果存在则查询大于等于这个日期的记录
if (params.get("startDate") != null) {
query.ge(Product::getCreate_time, params.get("startDate")); // ge是“greater than or equal to”的缩写
}
// 单独处理endDate,如果存在则查询小于等于这个日期的记录
if (params.get("endDate") != null) {
query.le(Product::getCreate_time, params.get("endDate")); // le是“less than or equal to”的缩写
}
if (params.get("id") != null) {
query.like(Product::getId, params.get("id"));
}
// 排序方式
if (params.get("value2") != null) {
String value2 = params.get("value2");
PageQueryValue2(query, value2);
}
Page<Product> page = new Page<>(1,10);
// 防空参数
if(params.get("currentPage")!=null && params.get("PageSize")!=null)
page = new Page<>(Long.parseLong(params.get("currentPage")),Long.parseLong(params.get("PageSize")));
// 执行分页查询
Page<Product> result = query.page(page);
// map返回筛选
R<Page<Product>> response = R.success(result);
response.setMap(params);
return response;
}
private void PageQueryValue2(LambdaQueryChainWrapper<Product> query, String value2)
{
switch(value2){
case "a":
break;
case "b":
query.orderByDesc(Product::getCreate_time);
break;
case "c":
query.orderByDesc(Product::getVisited_num);
break;
case "d":
query.orderByDesc(Product::getSold_num);
break;
case "e":
query.orderByDesc(Product::getRate);
break;
default:
break;
}
}
(3)XMLHttpRequest请求 FastAPI后端 多文件 HTML
html
<script>
document.getElementById('submitBtn').addEventListener('click', function() {
var files = document.getElementById('fileInput').files;
var formData = new FormData();
for (var i = 0; i < files.length; i++) {
formData.append('files', files[i]);
}
console.log(formData);
var xhr = new XMLHttpRequest();
xhr.open('POST', '/prod-api-xunlei/upload', true);
xhr.upload.onprogress = function(e) {
if (e.lengthComputable) {
var percentComplete = (e.loaded / e.total) * 100;
document.getElementById('progressBar').style.width = percentComplete + '%';
}
};
xhr.onload = function() {
if (xhr.status == 200) {
alert('Upload successful!');
} else {
alert('Upload error:'+xhr.responseText);
}
};
xhr.send(formData);
});
</script>
FastAPI
@app.post("/upload")
async def create_upload_files(request: Request,files: List[UploadFile] = File(...)):
if request.cookies.get("auth_token") != TOKEN:
return {"message": "Vaild token!"}
upload_dir = "/mnt/disk/yun_disk/upload"
os.makedirs(upload_dir, exist_ok=True) # 确保目录存在,如果不存在则创建目录
for file in files:
file_path = os.path.join(upload_dir, file.filename)
with open(file_path, "wb") as buffer:
shutil.copyfileobj(file.file, buffer)
(4)fetch 和 FastAPI GET请求
html
const queryParams = new URLSearchParams({
type: 'image', // 示例参数
year: '2022'
});
const response = await fetch(`/prod-api-xunlei/files?${queryParams.toString()}`);
const data = await response.json();
Py
@app.get("/files")
async def read_files(request: Request):
# 从请求中获取查询参数字典
query_params = dict(request.query_params)
print(query_params) # 打印查询参数,可以根据需要进行处理
# 可以根据参数执行特定逻辑
if "type" in query_params:
print(f"Filtering files of type: {query_params['type']}")
query_params.get('nginx_url')也可以 query_params.nginx_url会报错 返回502
更多推荐
所有评论(0)