您現在所在位置: 主頁(yè) > 關(guān)鍵詞優(yōu)化
使用ajax跨域調用springboot框架的api傳輸文件
更新時(shí)間:2026-05-05 01:57:10
這篇文章主要介紹了使用ajax跨域調用springboot框架的使用api傳輸文件,文中示例代(′▽?zhuān)?)碼介紹的跨域框架非常詳細,具有一定的調用的參考價(jià)值,感興趣的傳輸小伙伴們可以參考一下
在新項目中使用的是springboot編寫(xiě)的api,涉及到ajax跨域請求和傳輸文件的文件問(wèn)題,在這里記錄一下
首先是使用前臺頁(yè)面的代碼
<!DOCTYPE html>
<html>
<head>
<m(′?`*)eta charset='utf-8'>
<title>test_api</title>
<script type='text/javascript' src="jquery-1.7.2.js"></script>
<script type='text/ja??vascript'>
functio??n test(){
var obj = new Object;
obj??.name = $("#name").val??();
obj.age = $("#age").val();
var file = document.getElementB(′?`)yId("file").files[0];
var formData = new FormData();
formData.append("da??ta",JSON.strin??gify(obj));
formData.append("file",file);
$.ajax({
type:"po(′Д` )st",
url:"http://loc(′?ω?`)alhost:8187(′?`*)/test/upload",
contentType:false,
processData:false,
data:formData,
success:function(data){
alert(daヽ(′▽?zhuān)?ノta.msg);
}
});
}
</script>
</head>
<body>
<div cla(′▽?zhuān)?)ss=''>
<table>
<tr>
<td>sCompany:</td&g??t;
<td><input type='text' id="name" value="tom" /></td>
</tr>
<tr>
<td>scardtype:</td>
<td><input typ(╯°□°)╯e=??"text" id="age" val??ue='23' /></td>
</tr>
<tr>
<td>file:</td>
<td><input type="fil??e" id="file" />&??lt;/td>
</tr>
</table>
<input type='button' onclick="test();" value="提交ヽ(′?`)ノ" />
</div>
</body>
</html>
程序入口類(lèi)的代碼
pa(╬ ò﹏ó)ckage test;
import javax.servle??t.MultipartConfi??gElement;
import org.springframework.boot.Sprin??gApplication;
import org.springヽ(′?`)ノframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.Mul??tipartConfigFactory;
import or??g.springframework.context.annotation.Be??an;
import org.springframework.web.servlet.config.anno??tation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcCon??figurer;
import org.springframework.web.servlet.c(′?`)onf(′?`)ig.annotation.WebMvcCon??figurerAdapter;
/**
* Hello world!
*
*/
@SpringBootApplication
public class App
{
public static void main( String[] args )
{
SpringApplication.run(App.class, args);
}
//設置ajax跨域請求
@Bean
pu(′▽?zhuān)?blic WebMvc(?????)Configurer corsConfigurer(){
return new WebMvcConfigurerAdapter(){
@Override??
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("*");
}
};
}
@Bean
public MultipartConfi(╬?益?)gElement multipartConfigElement(){
MultipartConfigFactory fa(╯°□°)╯︵ ┻━┻ctory = new MultipartConfigFactory();
//設置上傳文件大小限制
factory.setMaxFileSize("10MB")(′?`);
//設置上傳總數據大小
faヽ(′ー`)ノctory.setMaxRequestSize((?????)"15MB");
return factor??y.createMultipartC(???)onfig();
}
}
package test.(′▽?zhuān)?controller;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import jav(°ロ°) !ax.serv??let(′?_?`).http.HttpServletRequest;
import org.springframework.web.bind.annotation.Request??Mapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;??
import org.springframework.web.multipヽ(′ー`)ノart.MultipartFile;
import org.springframework.web.multipart.Mult(??-)?ipartHttpServletRequest;
import test.model.UploadInfo;
import com.alibaba.fastjson.J??SON;
import com.alibaba.fastjson.JSONObject;
@RestController
@RequestMaヽ(′▽?zhuān)?ノpping("/test")
public class TestController {
/**
* 上傳文件
* @para??m req form請求
* @return json字符串
*/
@RequestMapping(value='/upload', method=RequestMethod.POST)
public String uploadFile(HttpServle??tRequest req){
// 返回結果用 jsヽ(′ー`)ノon對象
JSONObject returnObj = new JSONO??bject();
//從請求中獲取請求的json字符串
String strData = req.getParameter("data");
//將獲取到的JSO(′?ω?`)N字符串轉換為Imgidx對象
UploadInfo info = JSON.parseObject(strData, UploadInfo.class);
//獲取上傳的文件集合
List<MultipartFile> files = ((MultipartHttpServletRequest)req).getFiles("file");
MultipartFile file = files.get(0);
// 返回信息頭部
Map<String, String> header = new Ha(???)shMap<String, Stri(′?`)n???g>();
header.put("code", "0");
header.put("msg", "success");
File file1234 = new File(file.getOriginalFilename());
//插入數據的影響的數(shu)據條數
int result = 0;
//將文件上傳到save
if(!file.isEmpty()){
try{
byte??[] arr = new byte[1024];
BufferedOutputStream bos = new Bu(╯‵□′)╯fferedOutputStream(new FileOutputStream(file1234));
bos.write(arr);
bos.flush();
bos.close();
}catch(Exception e){
header.put("code", "-1");
header.put("ms(?Д?)g", "errorMsg:" + e.getMessage());
}
}else{
header.pu(′?ω?`)t("code", "-1");
header.put("msg", "err(′▽?zhuān)?)orMsg:上傳文件失敗,因為文件是跨域框架空的");
}
String returnStr = retur(′▽?zhuān)?nObj.toJ??SONString(header);
return returnStr;
}
}
以上就(jiu)是本文的全部?jì)热?,??望對大家的調用的學(xué)習有所幫助,也希望大家多多支持腳本之家。傳輸
文件來(lái)源:腳本之家
文件鏈接:https://??www.jb51.net/article/177174(′_`).htm
文件
