我对春季启动有点新意,我开发了以下逻辑:
这是我的要求。只是我想将图像上传到tomcat服务器,因为我已经尝试过使用spring boot
的逻辑@SpringBootApplication
public class MyApplication {
public static void main(String[] args) throws IOException {
new File(UploadController.uploadDir).mkdirs();
SpringApplication.run(MyApplication.class, args);
}
}
@RestController
public class UploadController() {
@RequestMapping("/test")
public String get(Model model) {
return "abc";
}
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public String uploadFiles(@RequestParam("uploadedFiles") MultipartFile[] uploadedFiles) throws IOException {
for(MultipartFile f : uploadedFiles) {
File file = new File(uploadDir + f.getOriginalFilename());
f.transferTo(file);
}
return "redirect:/";
}
}
在这里,获取请求工作正常。这是get
的代码public static String get() throws IOException {
HttpURLConnection conn = null;
BufferedReader br = null;
try {
URL url = new URL("http://localhost:8080/test");
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}
br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
return br.readLine();
} catch (MalformedURLException e) {
throw new IOException(e.getMessage());
} catch (IOException e) {
throw new IOException(e.getMessage());
} finally {
if (null != conn) {
conn.disconnect();
}
if (null != br) {
br.close();
}
}
}
但我不知道如何调用post方法。我尝试使用POST作为请求类型的相同逻辑。 BUt无法上传图片。任何人都可以从客户端发给我上传的代码吗?
答案 0 :(得分:0)
使用JSP和Javascript,代码如下所示:
JSP代码:
<input name="media[]" type="file" id="xmlTemplate" multiple>
Javascript代码:
var data = new FormData();
jQuery.each($('input[name^="media"]')[0].files, function(i, file) {
data.append("uploadedFiles", file);
});
var json = '{' + .... + ']}';//Some JSON I was also passing alongwith files
data.append('estimateInfo', new Blob([json], {
type: "application/json"
}));
$.ajax({
type : "POST",
processData: false,
dataType: 'json',
data: data,
cache: false,
contentType: false,
url: 'createEstimates',
success: function(result) {
},
error: function(result) {
}
});
控制器代码:
@RequestMapping(value = "/createEstimates", method = RequestMethod.POST, consumes = { "multipart/form-data" })
@ResponseBody
public EstimateResponse createEstimates(HttpServletRequest request,
@RequestPart("estimateInfo") EstimateInfo estimateInfo, @RequestPart("uploadedFiles") MultipartFile... files) {
}
如果要从Java客户端发送,则可以参考Upload Files Programmatically