Java模拟表单POST请求上传图片到图床

Java模拟表单POST请求上传文件

之前踩了很多坑,一步一步摸索上来了,直接复制下面的代码+spring的包,然后配置好mvc(前面的文章都有详细的配置代码了),直接运行,比其他文章好多了是不是?给点评论支持一下呗!

ApiController.java代码

别问我下面代码咋来的,之前的文章已经很详细了,就是MVC普通的流程走一下就行了

package biuaxia.mvc.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.activation.MimetypesFileTypeMap;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;

/** * Class Describe: * * @author biuaxia * @date 2018/11/17 * @time 23:19 */
@Controller
public class ApiController {

    @RequestMapping("api")
    public String showAjax() {
        return "api";
    }

    @RequestMapping(value = "api", method = RequestMethod.POST)
    @ResponseBody
    public String executeImport(MultipartFile file, HttpServletRequest request) throws IOException {

        FileInputStream fileInputStream = (FileInputStream) file.getInputStream();

        /*String urlStr = "在这里设置您的API";*/

        Map<String, String> textMap = new HashMap<>(1);

        /*textMap.put("key", "这里可以用来存放请求表单所需的数据");*/

        Map<String, FileInputStream> fileMap = new HashMap<>(1);

        fileMap.put("file", fileInputStream);

        String ret = formUpload(urlStr, textMap, fileMap, request);

        System.out.println(ret);

        return ret;
    }

    /** * 上传图片 * * @param urlStr * @param textMap * @param fileMap * @return */
    public static String formUpload(String urlStr, Map<String, String> textMap,
                                    Map<String, FileInputStream> fileMap, HttpServletRequest request) {
        String res = "";
        HttpURLConnection conn = null;
        //boundary就是request头和上传文件内容的分隔符,我模拟的浏览器中为35位
        String BOUNDARY = "---------------------------" + createRandCode();
        try {
            URL url = new URL(urlStr);
            conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(8000);
            conn.setReadTimeout(30000);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "Keep-Alive");
            /*conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");*/
            conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36");
            conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);

            //获得详细的conn内容,里面只有Ua,Content-Type
            Map<String, List<String>> maps = conn.getRequestProperties();
            /* for (String str : maps.keySet()) { List lists = maps.get(str) System.out.println(str + "\t\t\t\t" + lists) //User-Agent:[Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36] //Content-Type:[multipart/form-data; boundary=---------------------------QSZoQdar9QRF9pRWlSWR8oXpSpEUWIhEPvh] } */

            OutputStream out = new DataOutputStream(conn.getOutputStream());
            // text
            if (textMap != null) {
                StringBuffer strBuf = new StringBuffer();
                Iterator iter = textMap.entrySet().iterator();
                while (iter.hasNext()) {
                    Map.Entry entry = (Map.Entry) iter.next();
                    String inputName = (String) entry.getKey();
                    String inputValue = (String) entry.getValue();
                    if (inputValue == null) {
                        continue;
                    }
                    strBuf.append("\r\n").append("--").append(BOUNDARY).append(
                            "\r\n");
                    strBuf.append("Content-Disposition: form-data; name=\""
                            + inputName + "\"\r\n\r\n");
                    strBuf.append(inputValue);
                }
                /*System.out.println(strBuf);*/
                out.write(strBuf.toString().getBytes());
            }

            // file
            if (fileMap != null) {
                Iterator iterator = fileMap.entrySet().iterator();
                while (iterator.hasNext()) {
                    Map.Entry entry = (Map.Entry) iterator.next();
                    String inputName = (String) entry.getKey();
                    FileInputStream inputValue = (FileInputStream) entry.getValue();
                    if (inputValue == null) {
                        continue;
                    }
                    File file = asFile(inputValue, request.getServletContext().getRealPath("/uploadTempDir"));
                    //根据map集合中的file值(即文件地址)构造File对象
                    /*File file = new File(inputValue);*/
                    String filename = file.getName();
                    String contentType = new MimetypesFileTypeMap()
                            .getContentType(file);
                    //对文件后缀进行判断衔接
                    /*if (filename.endsWith(".png")) { contentType = "image/png"; } else if (filename.endsWith(".jpg")) { contentType = "image/jpg"; } else if (filename.endsWith(".jpeg")) { contentType = "image/jpeg"; } else if (filename.endsWith(".gif")) { contentType = "image/gif"; }*/
                    //判断内容是否为空
                    if (contentType == null || contentType.equals("")) {
                        contentType = "application/octet-stream";
                    }

                    StringBuffer strBuf = new StringBuffer();
                    strBuf.append("\r\n").append("--").append(BOUNDARY).append(
                            "\r\n");
                    strBuf.append("Content-Disposition: form-data; name=\""
                            + inputName + "\"; filename=\"" + filename
                            + "\"\r\n");
                    strBuf.append("Content-Type:" + contentType + "\r\n\r\n");

                    /*System.out.println(strBuf);*/
                    out.write(strBuf.toString().getBytes());

                    DataInputStream in = new DataInputStream(
                            new FileInputStream(file));
                    int bytes;
                    byte[] bufferOut = new byte[8192];
                    while ((bytes = in.read(bufferOut)) != -1) {
                        out.write(bufferOut, 0, bytes);
                    }
                    in.close();
                    file.delete();
                }
            }

            byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
            out.write(endData);
            out.flush();
            out.close();

            // 读取返回数据
            StringBuffer strBuf = new StringBuffer();
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    conn.getInputStream()));
            String line = null;
            while ((line = reader.readLine()) != null) {
                strBuf.append(line).append("\n");
            }
            res = strBuf.toString();
            reader.close();
            reader = null;
        } catch (Exception e) {
            System.out.println("发送POST请求出错。" + urlStr);
            e.printStackTrace();
        } finally {
            if (conn != null) {
                conn.disconnect();
                conn = null;
            }
        }
        return res;
    }

    public static String createRandCode() {
        char[] chars = new char[35];
        short start = '0';
        //如果此处没有加法,那么一个随机数取到1才会获得字符‘z’。所以此处+1即可,理论封顶是加到14,超过14就会取得其余字符,但我们通过了方法判断字符,不用担心!
        short end = 'z' + 14;
        for (int i = 0; i < chars.length; i++) {
            while (true) {
                char orderNum = (char) (Math.random() * (end - start) + start);
                if (Character.isLetter(orderNum) || Character.isDigit(orderNum)) {
                    chars[i] = orderNum;
                    /*System.out.println("orderNum:" + orderNum);*/
                    break;
                }
            }
        }
        String str = new String(chars);
        return str;
    }

  /* public static void inputstreamtofile(InputStream ins, File file) throws IOException { OutputStream os = new FileOutputStream(file); int bytesRead = 0; byte[] buffer = new byte[8192]; while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) { os.write(buffer, 0, bytesRead); } os.close(); ins.close(); }*/

    public static File asFile(InputStream inputStream, String tempPath) throws IOException {
        File tmp = File.createTempFile("biuaxia", ".jpg", new File(tempPath));
        OutputStream os = new FileOutputStream(tmp);
        int bytesRead;
        byte[] buffer = new byte[1024];
        while ((bytesRead = inputStream.read(buffer, 0, buffer.length)) != -1) {
            os.write(buffer, 0, bytesRead);
        }
        inputStream.close();
        return tmp;
    }
}

api.jsp代码

<%--
  Created by IntelliJ IDEA.
  User: biuaxia
  Date: 2018/11/17
  Time: 11:33
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="format-detection" content="telephone=no">
    <meta name="renderer" content="webkit">
    <meta http-equiv="Cache-Control" content="no-siteapp"/>
    <title>api文件上传 - biuaxiatitle>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/amazeui/2.7.2/css/amazeui.min.css" rel="stylesheet">
    <style> .footer p { color: #7f8c8d; margin: 0; padding: 15px 0; text-align: center; background: #2d3e50; } style>
head>
<body>
<header class="am-topbar am-topbar-fixed-top">
    <div class="am-container">
        <h1 class="am-topbar-brand">biuaxiah1>

        <button class="am-topbar-btn am-topbar-toggle am-btn am-btn-sm am-btn-secondary am-show-sm-only" data-am-collapse="{target: '#collapse-head'}"><span class="am-sr-only">导航切换span> <span class="am-icon-bars">span>button>

        <div class="am-collapse am-topbar-collapse" id="collapse-head">
            <ul class="am-nav am-nav-pills am-topbar-nav">
                <li><a href="index.do">首页a>li>
                <li><a href="calculator.do">计算器a>li>
                <li><a href="showUpload.do">原版文件上传a>li>
                <li><a href="ajax.do">ajax文件上传a>li>
                <li class="am-active"><a href="api.do">API文件上传a>li>
            ul>

            <div class="am-topbar-right">
                <button class="am-btn am-btn-secondary am-topbar-btn am-btn-sm"><span class="am-icon-pencil">span> 注册
                button>
            div>

            <div class="am-topbar-right">
                <button class="am-btn am-btn-primary am-topbar-btn am-btn-sm"><span class="am-icon-user">span> 登录
                button>
            div>
        div>
    div>
header>

<div class="am-g am-container">
    <div class="am-u-lg-12">
        <div class="am-alert am-alert-success" data-am-alert>
            <button type="button" class="am-close">×button>
            <p>提示:此接口为测试p>
        div>
        <input type="file" name="articleFile" id="articleFile" accept="image/*"><br>
        <button id="btn_import" onclick="return false">上传button>
        <br><br>
        <h3 id="showImgTitle">h3>
        <img id="showImgSrc" src="" alt="" width="100%" class="am-hide">
        <%--
                <form method="post" enctype="multipart/form-data">
                    <input type="file" name="articleFile" id="articleFile" accept="image/*"><br>
                    <button id="btn_import" onclick="return false">上传button>
                    <br><br>
                form>
        --%>
    div>
div>
<footer class="footer">
    <p>© 2014 <a href="http://www.yunshipei.com" target="_blank">AllMobilize, Inc.a> Licensed under <a href="http://opensource.org/licenses/MIT" target="_blank">MIT licensea>. by the AmazeUI Team.p>
footer>


<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js">script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/amazeui/2.7.2/js/amazeui.min.js">script>
<script> $("#btn_import").click(function () { var formData = new FormData(); formData.append("file", $("#articleFile")[0].files[0]); $.ajax({ url: 'api.do', type: 'post', data: formData, contentType: false, processData: false, cache: false, success: function (data) { data = JSON.parse(data); /* //Sina图床 if (data.code == 200) { $('#showImgSrc').attr('src', data.url); $('#showImgSrc').attr('alt', data.pid); $('#showImgSrc').removeClass('am-hide') $('#showImgTitle').html('' + data.pid + ' - ' + data.size + ''); } else { } */ //搜狗图床 if (data.state == 200) { $('#showImgSrc').attr('src', data.api_res.img_url); $('#showImgSrc').attr('alt', data.msg); $('#showImgSrc').removeClass('am-hide'); $('#showImgTitle').html('+ data.api_res.img_url + '">' + data.api_res.img_url + ''); } }, error: function () { alert("上传失败") } }); }) ; script>
body>
html>

提示

接口请自己寻找~

运行效果图

福利,咳咳,我专门缩小的哟~

你可能感兴趣的:(Java笔记)