Java如何在post一个文件的同时还提交一个json数据

Java如何在post一个文件的同时还提交一个json数据

使用 multipart/form-data

客户端

使用 OkhttpFastjson

OkHttpClient client = new OkHttpClient();

// 文件
File file = new File("D:\\17979625.jpg");

//json
JSONObject jsonObject = new JSONObject();
jsonObject.put("name", "KevinBlandy");


RequestBody requestBody = new MultipartBody.Builder()
	.setType(MultipartBody.FORM) 
	.addFormDataPart("file", file.getName(), RequestBody.create(MediaType.parse("image/png"), file)) 
	.addFormDataPart("json", null, RequestBody.create(MediaType.parse("application/json"), jsonObject.toJSONString()))
	.build();

Request request = new Request.Builder().url("http://localhost:8080/test/upload").post(requestBody).build();

	Response response = client.newCall(request).execute();
	
	response.body().string();

}

SpringBoot服务端

@PostMapping("/upload")
public Message<Void> upload(@RequestParam("file")MultipartFile multipartFile,
							@RequestParam("json")String json){
	
	LOGGER.debug("请求的文件:name={}, size={}", multipartFile.getOriginalFilename(), multipartFile.getSize());
	//请求的文件:name=17979625.jpg, size=113733 
	
	LOGGER.debug("请求的JSON:{}", json);
	// 请求的JSON:{"name":"KevinBlandy"}
	return Messages.OK;
}

Python服务端

from flask import Flask, render_template, request
import json

app = Flask(__name__)

@app.route('/test/upload', methods=['POST'])
def upload():
    file = request.files['file']
    print('读取到上传文件: %s' % file)
    # 读取到上传文件: <FileStorage: '17979625.jpg' ('image/png')>

    jsonVal = request.form['json']
    print('读取到json: %s' % jsonVal)
    # 读取到json: {"name":"KevinBlandy"}

    return json.dumps({'success': 1}), 200, {'ContentType':'application/json;charset=UTF-8'}

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8080, debug=True)
3 个赞

cxk

别发坤坤了。顶不住。

httpclient

跨平台调用第三方接口

pom依赖


        <dependency>
            <groupId>commons-httpclient</groupId>
            <artifactId>commons-httpclient</artifactId>
            <version>3.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpmime</artifactId>
            <version>4.5.3</version>
        </dependency>


示例代码


public void  getConnect(){

        CloseableHttpClient httpclient = HttpClients.createDefault();

        HttpPost httpPost = new HttpPost("http://127.0.0.1:8080/file/addFile");

        String fileInfo="/usr/root/personl/20190811";
        File file=new File("D:\\upload\\**.xls");
        System.out.println(file.getName());
        String s = null;
        try {
            MultipartEntityBuilder  builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            builder.setCharset(CharsetUtils.get("UTF-8"));
            builder.addTextBody("path",fileInfo,ContentType.TEXT_PLAIN.withCharset("UTF-8"));
            builder.addBinaryBody("file", new FileInputStream(file), ContentType.MULTIPART_FORM_DATA, file.getName());// 文件流
            HttpEntity httpEntity = builder.build();
            httpPost.setEntity(httpEntity);
            HttpResponse response=httpclient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            s = EntityUtils.toString(entity);
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(s);

    }

后端接口双参数:

(@RequestParam(“path”) String path, @RequestParam(“file”) MultipartFile file)

同理 如果多个不同参数:

(@RequestParam(“startTime”) String startTime,@RequestParam(“endTime”) String endTime)

     MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
     builder.addTextBody("startTime", startTime, ContentType.TEXT_PLAIN.withCharset("UTF-8"));
     builder.addTextBody("endTime", endTime, ContentType.TEXT_PLAIN.withCharset("UTF-8"));
     HttpEntity httpEntity=builder.build();
     httpPost.setEntity(httpEntity);
     HttpResponse response=httpclient.execute(httpPost);

后端dto接收(@RequestBody Dto dto)

    httpPost.addHeader("Content-Type", "application/json");
    httpPost.setEntity(new StringEntity(JSON.toJSONString(dto),"UTF-8")); //防止中文乱码
    CloseableHttpResponse response = httpclient.execute(httpPost);

搜嘎