文件图片远程url上传之ajax 加 body 参数传递

本文介绍了一个使用Spring MVC实现的远程图片上传接口。该接口通过POST方法接收前端传来的文件,并将其上传到指定服务器,同时返回上传结果。文章详细展示了如何配置HTTP客户端以支持文件上传及如何处理响应。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

@RequestMapping(value = {"/ImgUploadRemote.action"}, method = {org.springframework.web.bind.annotation.RequestMethod.POST})
	@ResponseBody
	public UploadResultDTO restUploadFilebyUrl(ModelMap model, HttpServletRequest request) {
		UploadResultDTO uploadResult  = null;
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());
		if (multipartResolver.isMultipart(request)) {
			Properties properties = RSBIUtils.getPropertiesValue("/application.properties");

			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			//从request中获取前端穿过来的文件
			List<MultipartFile> files = multipartRequest.getFiles("file");
			Map otherParams = new HashMap();
			otherParams.put("bizCode",properties.getProperty("dev.bizCode"));
			otherParams.put("sign",Utils.MD5(properties.getProperty("dev.bizCode")+files.get(0).getOriginalFilename()));

			String s = KanoUploadImgUtil.uploadFile(properties.getProperty("dev.fileupload.url"), files.get(0), null, otherParams);
			uploadResult = (UploadResultDTO) JSONObject.toBean(JSONObject.fromObject(s), UploadResultDTO.class);
			System.out.println("=====kkk====="+uploadResult.getData().get("httpUrl"));
		}
		return uploadResult;
	}


import java.util.List;
import java.util.Map;

/**
 *  @author youge
 *  @date 2020/10/9
 */
public class UploadResultDTO {
    private String code;
    private String message;
    private Map data;
    private List violationItems;

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public Map getData() {
        return data;
    }

    public void setData(Map data) {
        this.data = data;
    }

    public List getViolationItems() {
        return violationItems;
    }

    public void setViolationItems(List violationItems) {
        this.violationItems = violationItems;
    }
}

public static String uploadFile(String url ,MultipartFile file,Map<String,String>headerParams,
                                    Map<String,String>otherParams) {
        String result = "";
        //CloseableHttpClient实现了HttpClient接口
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            HttpPost httpPost=new HttpPost(url);

            //创建HttpClientBuilder设置属性
            HttpClientBuilder httpClientBuilder = HttpClientBuilder.create().setDefaultRequestConfig(RequestConfig.custom()
                    .setConnectionRequestTimeout(6000)
                    .setSocketTimeout(6000)
                    .setConnectTimeout(6000).build()).setRetryHandler(new DefaultHttpRequestRetryHandler(3, true));

            String fileName = file.getOriginalFilename();
            //添加header
            if(headerParams != null && !headerParams.keySet().isEmpty()){
                for (Map.Entry<String, String> entry : headerParams.entrySet()) {
                    httpPost.setHeader(entry.getKey(), entry.getValue());
                }
            }
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.setCharset(Charset.forName("utf-8"));
            //加上此行代码解决返回中文乱码问题
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            // 文件流
            builder.addBinaryBody("file", file.getInputStream(), ContentType.MULTIPART_FORM_DATA, fileName);
            for (Map.Entry<String, String> e : otherParams.entrySet()) {
                // 类似浏览器表单提交,对应input的name和value
                builder.addTextBody(e.getKey(), e.getValue());
            }

            HttpEntity entity = builder.build();
            httpPost.setEntity(entity);
            // 创建HttpClient对象,CloseableHttpClient实例的生成器
            httpClient = httpClientBuilder.build();

            // 发送HttpPost请求,获取返回值
            CloseableHttpResponse response=httpClient.execute(httpPost);
            result = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

// 图标上传
function uploadIcon(f_kpiId){
	var c_compId = curTmpInfo.compId;
	var b_compObj = findCompById(c_compId);
	var d_kpiJson = b_compObj.kpiJson;
	const f_kpiObj = findCurKpiObj(f_kpiId, d_kpiJson);
	$("#imgWait").show();
	var formData = new FormData();
	formData.append("file", document.getElementById("file1").files[0]);
	$.ajax({
		url: "ImgUploadRemote.action",
		type: "POST",
		data: formData,
		/**
		 *必须false才会自动加上正确的Content-Type
		 */
		contentType: false,
		/**
		 * 必须false才会避开jQuery对 formdata 的默认处理
		 * XMLHttpRequest会对 formdata 进行正确的处理
		 */
		processData: false,
		success: function (result) {
			if (result.code == "0") {
				// 获取图片的链接
				f_kpiObj.picurl = result.data.httpUrl;
				alert("上传成功!"+result.data.httpUrl);
			}else{
				alert(result.message);
			}
			$("#imgWait").hide();
		},
		error: function () {
			alert("上传失败!");
			$("#imgWait").hide();
		}
	});
}


   
 <br><span class="inputtext">图标: </span>'
		+'选择文件:<input type="file" id="file1" /><br />'
		+'<input type="button"  onclick="uploadIcon(\''+e_kpiId+'\')" value="上传" />'
		+' <img src="../resource/img/wait.gif" style="display:none" id="imgWait" />'
		+ '<br>



 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值