java后台用feign上传文件报错

liu_F_87 2019-05-29 09:19:50
异常:Caused by: com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class java.io.ByteArrayInputStream and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: org.springframework.web.multipart.commons.CommonsMultipartFile["inputStream"])

直接上代码,请高手给指点下....

上传图片代码,主要就是这三行, 跟createFileItem方法
FileItem fileItem = createFileItem(picturePath);
MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
JSONObject res = getFeign().uploadFile(multipartFile); (这个报错 )

    @Override
public void uploadLogoPicture(String picturePath) {
File logoPicture = new File(picturePath);
JSONObject jsonObject = new JSONObject();
jsonObject.put("fileName", logoPicture.getName());
jsonObject.put("fileSize", logoPicture.length());

FileItem fileItem = createFileItem(picturePath);
MultipartFile multipartFile = new CommonsMultipartFile(fileItem);

JSONObject res = getFeign().uploadFile(multipartFile); //报错行
log.info(res.toString());
res = getFeign().uploadLogo(jsonObject);
log.info(res.toString());
}

public FileItem createFileItem(String filePath) {
FileItemFactory factory = new DiskFileItemFactory(16, null);
String textFieldName = "file";
int num = filePath.lastIndexOf(".");
String extFile = filePath.substring(num);
FileItem item = factory.createItem(textFieldName, "multipart/form-data", true, filePath);
File newfile = new File(filePath);
int bytesRead = 0;
byte[] buffer = new byte[8192];
try {
FileInputStream fis = new FileInputStream(newfile);
OutputStream os = item.getOutputStream();
while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
return item;
}


feign接口函数
    /**
* 上传文件
* @param file
* @return
*/
@RequestLine("POST uploadFile.psp")
@Headers({"Content-Type: multipart/form-data", "UserName: admin", "PassWord: 123456"})
JSONObject uploadFile(@RequestParam MultipartFile file);


...全文
393 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
liu_F_87 2020-01-20
  • 打赏
  • 举报
回复
引用 1 楼 M义薄云天 的回复:
请问下搞定没有
看上面回复
liu_F_87 2020-01-20
  • 打赏
  • 举报
回复
搞定了

// 上传文件, 内部调用 sendPost()
private void uploadFile(String filePath) {
        String url = "http://" + getIp() + ":8765/uploadFile.psp";
        Map<String, String> requestHeader = new HashMap<>();
        requestHeader.put("UserName", "111");
        requestHeader.put("PassWord", "222");
        requestHeader.put("APIVersion", "x.x");
        requestHeader.put("IsAsyn", "true");

        Map<String, String> fileList = new HashMap<>();
        File file = new File(filePath);
        fileList.put(file.getName(), file.getAbsolutePath());
        sendPost(url, requestHeader, null, fileList, "", "");
    }


/**
     * 发送post请求
     *
     * @param requestUrl
     *            请求url
     * @param requestHeader
     *            请求头
     * @param formTexts
     *            表单数据
     * @param files
     *            上传文件
     * @param requestEncoding
     *            请求编码
     * @param responseEncoding
     *            响应编码
     * @return 页面响应html
     */
    public synchronized static String sendPost(String requestUrl, Map<String, String> requestHeader,
                                               Map<String, String> formTexts, Map<String, String> files,
                                               String requestEncoding, String responseEncoding) {

        OutputStream out = null;
        BufferedReader reader = null;
        String result = "";
        try {
            if (requestUrl == null || requestUrl.isEmpty()) {
                return result;
            }
            URL realUrl = new URL(requestUrl);
            HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
            connection.setRequestProperty("accept", "text/html, application/xhtml+xml, image/jxr, */*");
            connection.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:53.0) Gecko/20100101 Firefox/53.0");
            if (requestHeader != null && requestHeader.size() > 0) {
                for (Map.Entry<String, String> entry : requestHeader.entrySet()) {
                    connection.setRequestProperty(entry.getKey(), entry.getValue());
                }
            }
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod("POST");
            if (requestEncoding == null || requestEncoding.isEmpty()) {
                requestEncoding = "UTF-8";
            }
            if (responseEncoding == null || responseEncoding.isEmpty()) {
                responseEncoding = "UTF-8";
            }
            if (requestHeader != null && requestHeader.size() > 0) {
                for (Map.Entry<String, String> entry : requestHeader.entrySet()) {
                    connection.setRequestProperty(entry.getKey(), entry.getValue());
                }
            }
            if (files == null || files.size() == 0) {
                connection.setRequestProperty("content-type", "application/x-www-form-urlencoded");
                out = new DataOutputStream(connection.getOutputStream());
                if (formTexts != null && formTexts.size() > 0) {
                    String formData = "";
                    for (Map.Entry<String, String> entry : formTexts.entrySet()) {
                        formData += entry.getKey() + "=" + entry.getValue() + "&";
                    }
                    formData = formData.substring(0, formData.length() - 1);
                    out.write(formData.toString().getBytes(requestEncoding));
                }
            } else {
                String boundary = "-----------------------------" + String.valueOf(new Date().getTime());
                connection.setRequestProperty("content-type", "multipart/form-data; boundary=" + boundary);
                out = new DataOutputStream(connection.getOutputStream());
                if (formTexts != null && formTexts.size() > 0) {
                    StringBuilder sbFormData = new StringBuilder();
                    for (Map.Entry<String, String> entry : formTexts.entrySet()) {
                        sbFormData.append("--" + boundary + "\r\n");
                        sbFormData.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"\r\n\r\n");
                        sbFormData.append(entry.getValue() + "\r\n");
                    }
                    out.write(sbFormData.toString().getBytes(requestEncoding));
                }
                for (Map.Entry<String, String> entry : files.entrySet()) {
                    String fileName = entry.getKey();
                    String filePath = entry.getValue();
                    if (fileName == null || fileName.isEmpty() || filePath == null || filePath.isEmpty()) {
                        continue;
                    }
                    File file = new File(filePath);
                    if (!file.exists()) {
                        continue;
                    }
                    out.write(("--" + boundary + "\r\n").getBytes(requestEncoding));
                    out.write(("Content-Disposition: form-data; name=\"" + fileName + "\"; filename=\"" + file.getName() + "\"\r\n").getBytes(requestEncoding));
                    out.write(("Content-Type: application/x-msdownload\r\n\r\n").getBytes(requestEncoding));
                    DataInputStream in = new DataInputStream(new FileInputStream(file));
                    int bytes = 0;
                    byte[] bufferOut = new byte[1024];
                    while ((bytes = in.read(bufferOut)) != -1) {
                        out.write(bufferOut, 0, bytes);
                    }
                    in.close();
                    out.write(("\r\n").getBytes(requestEncoding));
                }
                //out.write(("--" + boundary + "--").getBytes(requestEncoding));这样写微信公众号开发上传素材有问题
                out.write(("--" + boundary + "--\r\n").getBytes(requestEncoding));
            }
            out.flush();
            out.close();
            out = null;
            reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), responseEncoding));
            String line;
            while ((line = reader.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送POST请求出现异常!");
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }
戎码一生灬 2020-01-16
  • 打赏
  • 举报
回复
需要添加feign支持form表单的pom依赖
M义薄云天 2020-01-15
  • 打赏
  • 举报
回复
请问下搞定没有

67,513

社区成员

发帖
与我相关
我的任务
社区描述
J2EE只是Java企业应用。我们需要一个跨J2SE/WEB/EJB的微容器,保护我们的业务核心组件(中间件),以延续它的生命力,而不是依赖J2SE/J2EE版本。
社区管理员
  • Java EE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧