JavaシミュレーションフォームPOST要求画像をベッドにアップロード

84905 ワード

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
"
).append("--").append(BOUNDARY).append( "\r
"
); strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"\r
\r
"
); 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
"
).append("--").append(BOUNDARY).append( "\r
"
); strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"; filename=\"" + filename + "\"\r
"
); strBuf.append("Content-Type:" + contentType + "\r
\r
"
); /*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
--"
+ BOUNDARY + "--\r
"
).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("
"
); } 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コード


<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>

ヒント
インタフェースは自分で探してください~
運転効果図
福祉、咳咳、私はわざわざ縮小しましたよ~