java 调用Spring接口上传文件及其他参数填充
程序员文章站
2022-06-29 09:43:29
第一步:在Spring配置中添加以下内容
第一步:在spring配置中添加以下内容
<!-- 配置multipartresolver 用于文件上传 使用spring的commosmultipartresolver -->
<bean id="multipartresolver"
class="org.springframework.web.multipart.commons.commonsmultipartresolver"
p:defaultencoding="utf-8" p:maxuploadsize="540000000" p:uploadtempdir="fileupload/temp">
</bean>
第二步:编写上传spring接口
/** * 上传专报 * * @param typeid * @param userid * @param file * @return */ @responsebody @requestmapping(params = "uploaddoc") public return uploaddoc(@requestparam(value = "file", required = true) multipartfile file,string newfilename) { return r = new return(); system.out.println(newfilename); try { // 3.保存word文件 if (file != null) { // 文件存入临时目录 string thisfile = savefile.save(file, newfilename); if(thisfile!=null){ r.sete(1); r.sets("上传专报成功!"); }else{ r.sete(0); r.sets("上传专报失败!"); } } } catch (exception e) { e.printstacktrace(); r.sets("系统异常"); } return r; } /** * 保存文件到临时目录 * * @param files * @param 保存文件路径包含文件名称 * @return */ public static string save(multipartfile files,string newfilepath) { string filename = files.getoriginalfilename(); if (filename == null) { return null; } file file = new file(newfilepath); if(!file.exists()){ try { fileoutputstream fop = new fileoutputstream(file); file.createnewfile(); // 获取文件字节 byte[] contentinbytes = files.getbytes(); fop.write(contentinbytes);// 写入本地 fop.flush(); fop.close(); return newfilepath; } catch (filenotfoundexception e) { e.printstacktrace(); } catch (ioexception e) { e.printstacktrace(); } } return null; }
第三步:编写上传程序
上传程序所需jar:httpclient-4.5.3.jar,httpmime-4.5.3.jar
/** * 上传文件到指定地址url * * @param 本地文件 * @param 请求接口路径 * @param newfilepath 其他参数 * @return 是否成功 */ public static boolean uploadfile(string filepath, string urlstr, string newfilepath) { try { string stestsetfile = newfilepath; string surl = urlstr;//"http://localhost:8080/qxfw/productcontroller.do?uploaddoc"; closeablehttpclient httpclient = httpclients.createdefault(); httppost uploadfile = new httppost(surl); multipartentitybuilder builder = multipartentitybuilder.create(); builder.addtextbody("newfilename", newfilepath, contenttype.text_plain); // 把文件加到http的post请求中 file f = new file(stestsetfile); builder.addbinarybody("file", new fileinputstream(f), contenttype.application_octet_stream, f.getname()); httpentity multipart = builder.build(); uploadfile.setentity(multipart); closeablehttpresponse response = httpclient.execute(uploadfile); httpentity responseentity = response.getentity(); string sresponse = entityutils.tostring(responseentity, "utf-8"); if (sresponse.contains("成功")) { return true; } else { return false; } } catch (exception e) { // todo: handle exception e.printstacktrace(); } return false; }
上一篇: ANDROID应用程序的混淆打包分享
下一篇: 自制豆芽方法特简单,让你吃得更安全健康